首页 > 代码库 > C++ Primer 第四版课后练习解答 习题1.18

C++ Primer 第四版课后练习解答 习题1.18

注意:本随笔是直接参考《C++Primer(第四版)习题解答(完整版)》中的。此处主要是便于本人以后反复阅读。

习题1.18

编写程序,提示用户输入两个数并将这两个数范围内的每个数写到标准输出。

【解答】

 while循环实现

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int v1, v2, low,up;
 7     cout << "Enter tow numbers " << endl;
 8     cin >> v1 >> v2;
 9     if (v1 < v2)
10     {
11         low = v1;
12         up = v2;
13     }
14     else
15     {
16         low = v2;
17         up = v1;
18     }
19     cout << "Values of " << low << " to " << up << " inclusive are: " << endl;
20     while (up >= low)
21         cout << low++ << " ";
22     cout << endl;
23     return 0;
24 }

 for循环实现

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int v1, v2, low,up;
 7     cout << "Enter tow numbers " << endl;
 8     cin >> v1 >> v2;
 9     if (v1 < v2)
10     {
11         low = v1;
12         up = v2;
13     }
14     else
15     {
16         low = v2;
17         up = v1;
18     }
19     cout << "Values of " << low << " to " << up << " inclusive are: " << endl;
20     for (int val = low; val <= up; ++val)
21         cout << val << " ";
22     cout << endl;
23     return 0;
24 }

 

C++ Primer 第四版课后练习解答 习题1.18