[英]print out all the numbers between user input and condition that are divisible by 2 and 3. while loop ask for another number
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Enter in value: " << endl;
cout << "\/";
cin >> x;
while(x < 0) {
cout << "value cannot be negative" << endl;
cin >> x;
}
for (int y = 0; y < x; y++)
{
if (y % 2 == 0 && y % 3 == 0) {
cout << y << " " << endl;
}
}
{int main();
int x = 100;
}
{
char ans = 'N';
do {
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N' :";
cin >> ans;
} while ((ans == 'Y') || (ans == 'y'));
}
system("pause");
return(0);
}
我的問題是,當我輸入一個數字時,它會顯示可被 2 和 3 整除的值,但是當“您想繼續嗎”部分運行時,它只會不斷詢問您是否要繼續而不是輸入另一個數字。
我不完全確定你想在這里做什么,或者這是否被允許,
{int main();
int x = 100;
}
但這可能是由於我的 cpp 知識。 無論如何,我做這些事情的方式是將您想要在 while 循環中重新運行的代碼包圍起來。 然后在您顯示可整除的數字后(在 while 循環內),您可以詢問用戶是否要繼續。 如果用戶想繼續,什么都不做,while 循環將再次運行。 如果用戶想退出,中斷 while 循環並可能終止程序。
int main(){
while(true) {
// your code that needs to be repeated goes here
int x;
cout << "Enter in value: " << endl;
cout << "\/";
cin >> x;
while(x < 0) {
cout << "value cannot be negative" << endl;
cin >> x;
}
for (int y = 0; y < x; y++){
if (y % 2 == 0 && y % 3 == 0) {
cout << y << " " << endl;
}
}
//ask the user to continue here
cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N' :";
cin >> ans;
//define the break condition for the loop
if((ans != 'Y') || (ans != 'y')){
break;
}
}
}
因為我們在開始時將 while 條件設置為true ,循環將再次執行,直到我們手動停止它。 為此,我們使用 break 語句並將其與用戶未輸入“Y”或“y”的條件相結合。 但是你可以給它任何你想要的條件。 現在,如果用戶被提示輸入一個字符,如果他輸入 'y',程序將前進到 while 循環的下一次迭代,重新開始代碼的除法部分。
我希望這是可以理解的和有幫助的,並為您的問題提供可能的解決方案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.