当前位置: 首页 > 文档资料 > C++大学教程 >

2.26 自测练习答案

优质
小牛编辑
117浏览
2023-12-01

2.1  a)顺序、选择和重复。b)if/else。c)计数器控制或确定。d)标记(记号、标志或哑元)。
2.2  x = X + 1;
x += 1;
++X;
x++;
2.3  a)  z= x++  + y;
b)  if ( count > 10 )
cout << "Count is greater than 10" << endl;
c) total -= --x;
d) q %= divisor;
q = q % divisor;
2.4    a) int sum, x;
b) x = 1;
c) sum = 0;
d) sum += x;或sum = sum + x;
e) cout << "The sum is:" << sum << endl;
2.5  如下所示:
1 // Calculate the sum of the integers from 1 to 10
2 #include <iostream.h>
3
4 int main()
5 {
6   int sum,x;
7   x= 1;
8   sum = 0;
9   while(x <= 10) {
10     sum += x;
11     ++x;
12  }
13  cout << "The sum is:" << sum << endl;
14  return 0;
15}
2.6    a) product = 25, x = 6;
b) quotient = 0, x = 6;
2.7    a) cin >> x;
b) cin >> y;
e) i = 1;
d) power = 1;
e) power *= x; 或 power = power * x;
f) i++;
g) if (i <= y)
h) cout << power << endl;
2.8 如下所示:
1 // raise x to the y power
2 #include <iostream.h>
3 int main()
4 {
5   int x, y, i, power;
6
7   i= 1;
8   power = 1
9   cin >> x;
lO  cin >> y;
11
12  while( i <=y ) {
13  power *= x ;
14      ++i;
15    }
16
17  cout << powe << endl;
18  return O;
19 }
2.9 a)不正确:while循环缺右花括号。
纠正:在++C;语句后面加上右花括号。
b)不正确:用流插入而不是流读取运算符。
纠正:将<<变为>>。
c)不正确:else后面的分号造成逻辑错误,第二个输出语句总是会执行。
纠正:将else后面的分号删除。
2.10 while结构中变量x的值永远不变。因此如果循环测试条件(z>=0)为true,则会生成无限循环。要防止生成无限循环,必须递减z,最终达到小于0。
2.11 a)不正确。default是可选的,如果不需要默认操作,则不需要default。
b)不正确。break语句用于退出switch结构。如果defalut为最后一个case,则不需要break语句。
c)不正确。使用&&运算符的两个关系表达式都为true时,整个表达式才能为true。
d)正确。

2.12 a) sum = 0
for ( count = 1; count <= 99; count += 2 )
sum += count;
b) cout << setiosflags(ios::fixed | ios::showpoint | ios::left)
<< setprecision(1) << setw (15) << 333.546372
<< setprecision(2) << setw (15) << 333.546372
<< setprecision(3) << setw (15) << 333.546372
<< endl;
输出如下:
333.5     333.55     333.546
c) cout << setiosflags(ios::fixed | ios::showpoint)
<< setprecision(2) << setw (10) << pow(2.5,3)
<< endl;
输出如下:
15.63
d) x = 1;
while (x <= 20) {
cout << x;
if (x % 5 == 0)
cout << endl;
else
cout << '\t';
x++
}
e) for (x = 1; x <= 20; x++) {
cout << x;
if (x % 5 == O)
cout << endl;
else
cout << '\t';
}

for (x = 1; x <= 20; x++)
if (x % 5 == O}
cout << x << endl;
else
cout << x << '\t';
2.13 a)不正确:while首部后面的分号会导致无限循环。
纠正:将分号换成"{"或删除";"和"}"。
b)不正确:用浮点数控制for重复结构。
纠正:用整数。并进行适当的计算以取得所要的值。
for(y=l;y!=10;y++)
cout << ( static cast<float>(y) / lO  ) << endl;
c)不正确:第一个case的语句中缺少break语句。
纠正:第一个case语句中补上break语句。注意,如果程序员要让case 1语句每次执行时都执行case 2的语句,则这不是错误。
d)不正确:while重复条件中使用不正确的关系运算符。
纠正:用"<="而不用"<",或将10变为11。