Midterm Review Questions Solutions¶
Write a function called
isPositive(x)that returnstrueifxis greater than 0, andfalseifxis 0 or less. For example:isPositive(0)returnsfalseisPositive(4.0)returnstrueisPositive(-5.3)returnsfalseSample solution:
boolean isPositive(float x) { if (x > 0) { return true; } else { return false; } } // or ... boolean isPositive(float x) { return x > 0; }
Write a function called
sign(x)that returns the sign ofx, i.e. -1 ofxis less than 0, 0 ifxis equal to 0, and 1 ifxis greater than 0. For example:sign(-4)returns -1sign(-5.3)returns -1sign(0)returns 0sign(4)returns 1sign(53.2)returns 1Sample Solution:
int sign(float x) { if (x < 0) { return -1; } else if (x > 0) { return 1; } else { return 0; } }
Write a function called
min(x, y)that returns the smaller ofxandy. For example:min(1, 2)returns 1min(2, 1)returns 1min(-85, 2)returns 2min(3, 3)returns 3Sample solution:
int min(int x, int y) { if (x < y) { return x; } else { return y; } }
Write a function called
dist(x, y)that returns the positive difference betweenxandy.dist(1, 2)returns 1dist(2, 1)returns 1dist(-5, 2)returns 7dist(3, 3)returns 0Sample solution:
int dist(int x, int y) { float d = x – y; if (d < 0) { return -d; } else { return d; } } // or ... int dist(int x, int y) { return abs(x - y); }