[英]Misunderstanding C++ Primer 5th Edition Exercise 1.19 “The If Statement”?
每个人。 在 C++ Primer 5th Edition 的练习 1.19 中,它说
Revise the program you wrote for the exercises in 1.4.1 (p.
13) that printed a range of numbers so that it handles input in which the first
number is smaller than the second
我的代码在运行时似乎满足要求:
#include <iostream>
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
if (v1 < v2) {
while (v1 <= v2) {
std::cout << v1 << std::endl;
++v1;
}
}
else {
std::cout << "First number is bigger." << std::endl;
}
return 0;
}
然而,当我检查两个不同的站点来检查我的答案时,它们在 if 语句中都有不同的语句:
// Print each number in the range specified by two integers.
#include <iostream>
int main()
{
int val_small = 0, val_big = 0;
std::cout << "please input two integers:";
std::cin >> val_small >> val_big;
if (val_small > val_big)
{
int tmp = val_small;
val_small = val_big;
val_big = tmp;
}
while (val_small <= val_big)
{
std::cout << val_small << std::endl;
++val_small;
}
return 0;
}
两个答案似乎都有一个临时 int 变量,我不确定它如何或为什么更适合该问题。
正在修订的练习内容如下:
编写一个程序,提示用户输入两个整数。 打印由这两个整数指定的范围内的每个数字。
当练习 1.19 要求您更改程序以便它“处理”第一个数字较小的输入时,这意味着程序仍应打印范围内的每个数字。 我还认为该练习是假设您的程序的早期版本仅在第一个数字大于或等于第二个数字时才有效。
换句话说,您需要编写一个程序,其中以下两个输入的输出相同:
输入:5 10
输出:5 6 7 8 9 10输入:10 5
输出:5 6 7 8 9 10
您展示的示例解决方案是通过检查输入数字是否按特定顺序来实现这一点,如果不是,则交换它们。 这确保了这两个值的顺序是程序其余部分所期望的。
我猜在任务中应该是“如果第一个数字大于第二个”,因为另一种情况已经在您的代码中处理过,而这个只是打印一条错误消息。
在示例中,如果第一个值大于第二个值,则它们只是交换值。
我尝试了我的代码版本,它看起来像这样:
//enter code here
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
//write a program that prompts the user for 2 integers
// print each number in the range specifies by those 2 integers
int val1 = 0, val2 = 0;
cout << "Enter 2 integer values: ";
cin >> val1 >> val2;
cout << endl;
// my reason for using if is to always make sure the values are in incrementing order
if (val1 > val2)
{
for (int i = val2; i <= val1; ++i)
cout << i << " ";
}
else
{
for (int i = val1; i <= val2; ++i)
cout << i << " ";
}
cout << endl;
`
无论您的输入是 5 10 还是 10 5:您的输出将始终是:5 6 7 8 9 10。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.