好记性不如烂笔头,分享下我做的练习:
1、设货物运费每吨单价 p(元)与运输,距离 s(公里)之间有如下关系:
输入要托运的货物重量为 w
吨,托运距离 s 公里,计算总运费 t :
t = p * w * s
按照一般思路范围从小到大进行筛选,要写五个判断,而观察一下里程与单价的变化规律可以发现,从100公里开始每加100公里减少2.5元单价,据此可以只写三个判断,以规律囊括中间100到400的单价变化,实现代码:
float w, s, t, p;
cout << "托运重量(/t): ";
cin >> w;
cout << "托运里程(/km): ";
cin >> s;
if (s / 100 <1)
p = 30;
else
if (s / 100>= 4)
p = 20;
else
p = 30 -(int (s / 100))*(2.5);
t = p*w*s;
cout << "托运费用: " << t << endl;
2、输入三个整数,按从小到大顺序输出。(if else/三目)
这题要求两种写法,我们先把if else写法写出来:
int x, y, z, a=0,b=0, c=0;
cout << "输入三个整数: ";
cin >> x >>y >> z;
if (x >= y) {
if (x >=z) {
a = x;
if (y>= z) {
b =y, c = z;
}
else {
b =z, c = y;
}
}
else {
a = z, b= x, c = y;
}
}
else if(y>=z) {
a = y;
if (x >=z) {
b = x, c= z;
}
else {
b = z, c= x;
}
}
else {
a = z, b =y, c = x;
}
cout << "a:" << a << " b: " << b << " c:" << c << endl;
cout << "x:" << x << " y: " << y << " z:" << z << endl;
但是三目的稍微麻烦一些,运算符优先级判断要熟练
int x, y, z, a=0,b=0, c=0;
cout << "输入三个整数: ";
cin >> x >>y >> z;
x >= y ? (x >=z ? (a = x, (y >= z ? (b = y, c = z) : (b = z, c = y))) : (a = z, b = x, c =y)) : (y >= z ? (a = y, (x >= z ? (b = x, c = z) : (b = z, c = x))) : (a= z, b = y, c = x));
cout << "a:" << a << " b: " << b << " c:" << c << endl;
cout << "x:" << x << " y: " << y << " z:" << z << endl;
由于三目的优先级高于赋值符,经常容易漏括号导致赋值错误,所以还是要养成随手加括号的习惯啊