如何解决即使if为真,为什么if语句始终是else部分?
最后的if语句有问题。 **如果用户输入的数字的小数之和等于数字本身,请说“ ...”。否则,说“ .....” **
问题是它总是将if部分跳到else。
这是大学的一项任务,没有功课就什么也没有,只是培训。如果您有更好的建议,我也将不胜感激。
谢谢!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage,let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i,3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(),sums.end(),0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
解决方法
输入if
部分后,将不再输入else
部分。请注意,您的if/else
没有被循环包围。因此,当控制权一次通过时,例如输入n==0
后,它就已经过去了,不会再次进入if
和else
部分。
尝试类似
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。