【发布时间】:2019-07-19 12:00:28
【问题描述】:
我是这里的新手编码员,我似乎无法弄清楚要在我的代码中添加什么以使其正确。如果用户没有回答“您要进行另一个计算 Y 还是 N?”,则应该再次询问用户。正确。我希望它重复要求用户输入 y 或 n 如果他们输入其他内容。我觉得很明显我只是想念它。这是给学校的,要清楚。
我尝试过嵌套一个 do while 循环和一个 if 语句,但只是为了得到运行时错误
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
当我尝试添加嵌套的 do while 循环并输入除 y 或 n 之外的字符答案时,它会转到它不应该包含的程序部分。
*这是我的第一个问题,所以我希望我做对了
【问题讨论】:
-
将提示包装在另一个
do while -
不要把所有东西都塞进
main,而是创建一个提示用户并返回结果的函数。
标签: c++ loops while-loop do-while