[英]Why my program displays the output multiple times
有人可以幫我修復此代碼。 當輸入等於或小於零的值時,我需要我的輸出顯示無效值輸入,但是,輸出顯示數百行。 我發現了一些示例,向值添加 (++;) 以解決此問題。 但是,如果我使用 ++,輸出會顯示(多次無效數字和 - 數字。如果我更改為 - 輸出會再次顯示無效值輸入數百次。
謝謝你的幫助
#include <iostream>
using namespace std;
int main()
{
int c0 ;
cout << " Enter a non negative number greater than 0: ";
cin >> c0;
while (c0 != 1)
//if number is odd i divide it by 2 i have a remainded of 1
//if number is even i divide it by 2 i have a remainded of 0
{
if (c0 % 2 == 1)
c0 = (3 * c0) + 1;
if (c0 <= 0)
{
cout << "Invalid value input " ;
}
else
c0 /= 2;
cout << c0 << '\n';
}
}
很簡單,因為你cout << "Invalid value input " ;
所以你要多次顯示數字cout << "Invalid value input " ;
循環內。 如果你把它放在循環之前,它只會顯示一次。
cout << " Enter a non negative number greater than 0: ";
cin >> c0;
if (c0 <= 0)
{
cout << "Invalid value input " ;
}
while (c0 != 1)
{
...
}
接下來要考慮的是當用戶輸入無效數字時您希望發生什么。 您想中止程序嗎? 您要再次詢問用戶嗎? 目前該程序將繼續進行,就好像什么都沒發生過一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.