[英]How to add a loop to this program to ensure user enters positive number, if negative make them retype it?
我怎樣才能確保用戶輸入一個正數,如果它是負數會給他們一個錯誤並讓他們重新輸入它?
int main()
{
float sq, n;
cout << "Enter any number:";
cin >> n;
sq = sqrt(n);
cout << "Square root of " << n << " is " << sq;
return 0;
}
這可以通過 do-while 循環輕松實現:
int num = 0;
do {
std::cin >> num;
} while (num < 0)
在這里,你可以使用while循環和while循環中的if-else語句。
int main()
{
float sq;
int n;
cout << "Enter any number:\n";
while (cin >> n) {
if (n < 0)
cout << "enter a positive number\n";
else {
sq = sqrt(n);
cout << "Square root of " << n << " is " << sq << '\n';
cout << "Enter any number: \n";
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.