c++while函数例题
时间: 2024-09-07 11:01:00 浏览: 54
在C++中,while
语句用于条件循环,当给定的条件为真时,执行循环体中的代码,直到条件变为假为止。这是一个基本的while循环的例子:
#include <iostream>
int main() {
int number = 0;
std::cout << "Enter a positive integer: ";
std::cin >> number;
// While loop that continues as long as the number is greater than zero
while (number > 0) {
std::cout << "You entered: " << number << "\n";
std::cout << "Would you like to enter another number? (yes/no): ";
char response;
std::cin >> response;
if (response == 'y' || response == 'Y') {
std::cout << "Please enter another number: ";
std::cin >> number;
} else {
break; // Exit the loop when user enters no or 'n'
}
}
return 0;
}
在这个例子中,程序首先要求用户输入一个正整数。然后,只要用户输入的是 'y' 或 'Y',就会继续询问是否要输入另一个数字,如果输入 'n' 或 'N',则跳出循环。
相关推荐

















