【发布时间】:2020-05-22 23:50:11
【问题描述】:
我尝试编写一个程序来获取数字的根,例如,如果您在菜单中输入 3,它将尝试找到您的数字的第三个根,所以如果您输入 8,它会给您 2,但是这儿存在一个问题。我正在使用 for 循环,如果我尝试在循环中为我的条件定义一个 else,它也会打印 cout 与定义循环一样多次。我应该怎么做才能解决这个问题?有人可以帮帮我吗?我应该改用while吗?请保持你的答案简单明了。 这是我的代码:
system("cls");
system("color 78");
int roots;
cout << "Which root are you trying to find out?" << endl;
cin >> roots;
switch (roots)
{
case 1:
{
system("cls");
double po;
cout << "Please enter the number you wnat to see its first root: " << endl;
cin >> po;
cout << "Your number's first root is: " << po << endl;
Backhome();
}
break;
case 2:
{
system("cls");
double p;
cout <<"Please enter the number you want to find its second root:"<< endl;
cin >> p;
cout <<"Your number's second root is: "<< sqrt(p) << endl;
cout << "Your number's second root is: " << "-" << sqrt(p) << endl;
Backhome();
}
break;
case 3:
{
system("cls");
double th;
cout << "Please enter the number you want to find its third root: "<< endl;
cin >> th;
for (int i= -10000 ; i <= 10000; i++)
{
if ((i*i*i) == th)
{
cout << "Your number's third root is: " << i << endl;
}
else
{
cout << "Your number doesn't have a third root." << endl;
}
}
Backhome();
}
break;
case 4:
{
system("cls");
double foot;
cout << "Enter the number you want to see its fourth root: " << endl;
cin >> foot;
for (int i = -10000; i <= 10000; i++)
{
if ((i*i*i*i) == foot)
{
cout << "Your number's fourth root is: " << i << endl;
}
else
{
cout << "Your number doesn't have a fourth root." << endl;
}
}
Backhome();
}
break;
case 5:
{
system("cls");
double pive;
cout << "Enter the number you want to see its fifth root: " << endl;
cin >> pive;
for (int i = -10000; i <= 10000; i++)
{
if ((i*i*i*i*i) == pive)
{
cout << "Your number's fifth root is: " << i << endl;
}
else
{
cout << "Your number doesn't have a fifth root." << endl;
}
}
Backhome();
}
(简而言之,问题在于循环中的 else 被打印的次数与定义循环的次数一样多,我不希望这种情况发生。我会很感激你的帮助。)
【问题讨论】:
标签: c++ visual-studio for-loop console-application dev-c++