我写了一个函数来计算数字的平方并试图包含所有可能的输入。
总体上,它与数字输入一起运行良好,但当我输入字母时,它会在屏幕上启动无限循环打印语句。我们都知道,在计算机内部,单个字符,例如"A或a或b或B"等,由整数表示,并且我从我的老师那里学到,我们可以使用整数数据类型将单个字符存储到变量中。我不是在谈论指代字符的字符串。这个程序对单个字符造成了问题!
#include <iostream>
#include <string>
using namespace std;
void squire();
int main() {
squire();
}
void squire() {
double num = 1.0, pow = 1.0, Squire_Number = 1.0;
char ans;
reStart:
cout << "please Enter the Number: \n";
cin >> num;
cout << "please enter the nmber you want to power the number with: \n";
cin >> pow;
if (num > 0 && pow>0) {
for (int i = 1; i <= pow; i++) {
Squire_Number *= num;
}
cout << pow << " power of " << num << " is equil to : " << Squire_Number;
goto option;
}
else
{
cout << "Please enter Positve Integers. \n" ;
option:
cout<< "\nPease type 'Y' to Enter the values again OR type 'c' to Exit ! \n";
cin >> ans;
if (ans == 'y' || ans == 'Y') {
goto reStart;
} else if (ans == 'c' || ans == 'C') {
cout << "thank you for using our function. \n";
}
}
return;
}
for (int i = 1; i <= pow; i++)
与for (int i = 0; i < pow; i++)
相同,只是更多的人会觉得它很奇怪,并且会想知道你是否有一个偏移一的错误。 - user4581301std::toupper
和std::tolower
。这将简化您的if
语句,例如:if (toupper(ans) == 'Y')
。 - Thomas Matthews