C++入门第5版练习1.19 "The If Statement"的误解 ?

Misunderstanding C++ Primer 5th Edition Exercise 1.19 "The If Statement"?

本文关键字:If The Statement 误解 门第 5版 练习 C++      更新时间:2023-10-16

每个人。在C++初级读本第5版的练习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;
}

两个答案似乎都有一个temp-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。