Processing test #1 - Answers
// Processing test 1
void setup() {
size(600,400);
background(200); // light gray
// test Problem #1: MyPower():
//println(MyPower(2,3),MyPower(2,-3));
// test Probem #2: int2String()
// println(Int2String(23),Int2String(987004),Int2String(23034));
// println(Int2String2(23),Int2String2(987004),Int2String2(23034));
// test Problem #3
// VerticalCircles();
// test Extra credit
// CrossHatch();
}
// ======================= Problem #1
float MyPower(float base, int exponent) {
int i;
float answer = 1.0;
if (exponent == 0)
return answer;
if (exponent > 0) {
for (i = 1; i <= exponent; ++i)
answer *= base;
}
else {
for (i = -1; i >= exponent; --i)
answer /= base;
}
return answer;
}
// ======================== Problem #2 Version 1
String Int2String(int n) {
String sn = str(n);
if (n < 1000)
return sn;
return sn.substring(0,sn.length()-3) + "," + sn.substring(sn.length()-3);
}
// ======================== Problem #2 Version 2
String Int2String2(int n) {
int thousands, ones;
if (n < 1000) // no comma necessary
return str(n);
thousands = n / 1000; // remember: this is integer division
ones = n % 1000;
if (ones >= 100)
return str(thousands) + "," + str(ones);
if (ones >= 10)
return str(thousands) + ",0" + str(ones);
return str(thousands) + ",00" + str(ones);
}
// ==================================== Problem #3
void VerticalCircles() {
int i;
line(0,0,600,400); // this line is behind the circles, so must be drawn first
// there are 9 circles with diameter 50
for (i = 0; i < 9; i++) {
fill(i*255/8); // when i == 0, this is black, when i == 8, this is white
circle(300,i*50,50);
}
line(600,0,0,400); // this line is on top of the circles
}
// ================================= Extra credit
void CrossHatch() {
background(230); // close to white
for (int i = 0; i <= 600; i += 50)
DrawFromABottomPoint(i);
}
void DrawFromABottomPoint(int bottom) {
for (int i = 0; i <= 600; i += 50)
line(bottom, 400, i, 0);
}