打卡cs106x(Autumn 2017)-lecture2
1、parameterMysteryBCA
What is the output of the following code?
void mystery(int& b, int c, int& a) {a++;b--;c += a;
}
int main() {int a = 5;int b = 2;int c = 8;mystery(c, a, b);cout << a << " " << b << " " << c << endl;return 0;
}
解答:
5 3 7
2、 xkcdDatingRange
Write a function named xkcdDatingRange
that accepts three parameters: an integer for a person's age, and two integer references for a minimum and maximum, and that fills the min/max integers with the person's xkcd "dating range" as described in the following web comic strip:
- xkcd: Dating Pools
Your minimum xkcd dating age is half your own age plus 7. Your maximum xkcd dating range is your own age, minus 7, then doubled. For example, the call of datingRange(48, min, max);
sets min
to 31
and max
to 82
. You may assume that the age value passed is a non-negative integer.
解答:
#include <iostream>
#include "console.h"
#include "simpio.h"using namespace std;/** xkcd漫画约会年龄区间算式:* 你最小的xkcd约会年龄是你的年龄除以2再加7* 你最大的xkcd约会年龄是你的年龄减去7再乘2
*/
void xkcdDatingRange(int age, int& min, int& max) {min = (age / 2) + 7;max = (age - 7) * 2;
}int main() {int age = getInteger("请输入你的年龄: ");int min, max;xkcdDatingRange(age, min, max);cout << "按照xkcd漫画的算式,你的约会年龄区间为: ";cout << min << "~" << max << endl;return 0;
}
3、quadratic
Write a function named quadratic
that computes roots of quadratic equations. Recall that a quadratic equation is one of the form, . Your function accepts five parameters: The integer coefficients
a
, b
, and c
, and two real number references root1
and root2
. Your function should compute the two integer roots of the quadratic equation and store them into the two reference parameters. For example, the equation has roots of x = 4 and x = -1, so the call of
quadratic(1, -3, -4, root1, root2);
should set root1
to 4
and root2 to -1
. You may assume that the function has two real roots. Recall the quadratic formula:
解答:
#include <iostream>
#include <cmath>
#include "console.h"
#include "simpio.h"using namespace std;void quadratic(int a, int b, int c, double& root1, double& root2) {root1 = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);root2 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
}int main() {// x**2 - 3x -4 = 0double root1, root2;quadratic(1, -3, -4, root1, root2);cout << "x**2 - 3x -4 = 0的root1为" << root1 << " root2为" << root2 << endl;return 0;
}
4、returnMystery1
What is the output from the following C++ program?
int mystery(int b, int c) {return c + 2 * b;
}
int main() {int a = 4;int b = 2;int c = 5;
a = mystery(c, b);c = mystery(b, a);cout << a << " " << b << " " << c << endl;return 0;
}
解答:
12 2 16