簡體   English   中英

誤解 C++ Primer 第 5 版練習 1.19 “If 語句”?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM