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

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

习题1.4

我们的程序利用内置的加法操作符“+”来产生两个数的和。编写程序,使用乘法操作符“*”产生两个数的积。

【解答】

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5     std::cout << "Enter two numbers:" << std::endl;
 6     int v1, v2;
 7     std::cin >> v1 >> v2;
 8     std::cout << "The product of" << v1 << " and " << v2
 9         << "is " << v1*v2 << std::endl;
10 
11     return 0;
12 }


本人示例代码:

 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     cout << "Enter two numbers:" << endl;
 6     int v1, v2;
 7     cin >> v1 >> v2;
 8     cout << "The product of" << v1 << " and " << v2
 9         << " is " << v1 * v2 << endl;
10 
11     return 0;
12 }

具有交互性的示例代码:
提前使用了后面章节的do while语句知识。

 1 #include <iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     string rsp;
 8     do
 9     {
10         cout << "Please enter two values: ";
11         int val1, val2;
12         cin >> val1 >> val2;
13         cout << "The product of "
14             << val1 << " and " << val2
15             << " = " << val1 * val2 << "\n\n"
16             << "More?[Yes][No]";
17         cin >> rsp;
18     } while (!rsp.empty() && (rsp[0] != 'n') && (rsp[0] != 'N'));
19     return 0;
20 }

 

posted @ 2017-03-10 00:27  haihai187  阅读(182)  评论(0)    收藏  举报