演習の解答例

問題 1

float area(float a, float b, float c) {
  return a * b * c;
}

void setup() {
  noLoop();
}

void draw() {
  println(area(1, 1, 1));
  println(area(2, 3, 4));
  println(area(0.5, 2.1, 4.4));
}

実行結果

1.0
24.0
4.62

問題 2

int squareSum(int[] x) {
  int sum = 0;
  for (int i = 0; i < x.length; ++i) {
    sum += x[i] * x[i];
  }
  return sum;
}

void setup() {
  noLoop();
}

void draw() {
  int[] x = {1, 3, 5, 7, 9, 11, 13, 15};
  println(squareSum(x));
}

実行結果

680

問題 3

int charCount(String s, char c) {
  int count = 0;
  for (int i = 0; i < s.length(); ++i) {
    if (s.charAt(i) == c) {
      count += 1;
    }
  }
  return count;
}

void setup() {
  noLoop();
}

void draw() {
  String s = "yosuke onoue";
  println(charCount(s, 'y'));
  println(charCount(s, 'o'));
  println(charCount(s, 'u'));
}

実行結果

1
3
2

問題 4

float myDist(float x1, float y1, float x2, float y2) {
  float dx = x1 - x2;
  float dy = y1 - y2;
  return sqrt(dx * dx + dy * dy);
}

void setup() {
  noLoop();
}

void draw() {
  float d = myDist(-100, -100, 100, 100);
  println(d);
}

実行結果

282.8427

問題 5

void drawCircles(int cx, int cy, int r, int n) {
  int dr = r / n;
  stroke(0);
  noFill();
  for (int i = 1; i <= n; ++i) {
    ellipse(cx, cy, 2 * dr * i, 2 * dr * i);
  }
}

void setup() {
  size(400, 400);
}

void draw() {
  background(255);
  drawCircles(100, 100, 100, 5);
  drawCircles(100, 300, 100, 4);
  drawCircles(300, 100, 100, 3);
  drawCircles(300, 300, 100, 2);
}

実行例

fig2

問題 6

String today() {
  return "" + year() + '/' + month() + '/' + day();
}

void setup() {
  noLoop();
}

void draw() {
  println(today());
}

実行例

2020/5/25

問題 7

int sum(int[] a, int k) {
  if (k == 0) {
    return 0;
  }
  return a[k - 1] + sum(a, k - 1);
}

int sum(int[] a) {
  return sum(a, a.length);
}

void setup() {
  noLoop();
}

void draw() {
  int[] a = {
    94921,
    2398,
    71531,
    9560,
    83280,
  };
  println(sum(a));
}

実行結果

261690

results matching ""

    No results matching ""