if else 语句混淆了 c++
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i = 0; i <= positiveInteger; i++)
{
if ( positiveInteger >= 0 )
{
result += i;
}
else
{
cout << "Please input a positive integer." << endl;
}
}
cout << result;
return 0;
}
上面有一个 for 循环,中间有一个 if else 语句。我很困惑,因为我希望它是这样的,所以当我输入一个非负整数时,它会循环 if 结果。但我希望它是这样,如果我输入一个负数,它会说请输入一个正整数。这就是为什么我在 if 语句中设置它,只有上面的数字和 = 到 0 才会返回结果,但如果我输入一个负数,我只会得到 0 我希望它说“请输入一个正整数”。我不明白我做错了什么。是不是 if 语句 if true 会拉动 if,如果 if not true 会拉动 else?或者我错过了什么?
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
cout << "Please input an integer up to 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i = 0; i <= positiveInteger; i++)
{
if ( positiveInteger >= 0 )
{
result += i;
}
else
{
cout << "Please input a positive integer." << endl;
}
}
cout << result;
return 0;
}
Above I have a for
loop with an if else statement in the center. I am confused because I want it to be so when I enter a integer that is not negative it will loop the if result. But I want it to be so if I put in a negative number it says please input a positive integer. That's why I set it so in the if statement only numbers above and = to 0 would return the result, but if I enter a negative number I just get 0 I want it to say "Please input a positive integer". I don't understand what I'm doing wrong. Isn't the if statement if true pulls the if and if its not true pulls the else? Or am I missing something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果输入负数,则永远不会进入循环。更适合这种情况的方法是:
If you enter a negative number, you never get to enter the loop. An approach that fits better to such cases is:
如果我答对了,你想
1.输入一个数字;
2.1 如果数字是正数,则循环遍历它。
2.2 如果结果为负,则显示错误消息。
问题是你的循环,其中条件是检查 i (为零)是否小于数字。但是,如果您输入负数,i 将大于正整数,并且您将不会循环 if 。我修复了你的代码
If I got it right, you want to
1. input a number;
2.1 If the number is positive you loop through it.
2.2 If it's negative you show the error message.
The problem is your loop, where the conditional is, checks if i (which is zero) is smaller then the number. However if you input a negative number i will be bigger then positiveInteger and you won't loop through the if. I fixed your code
我认为你的代码会从一些重新排列中受益。我会把它构造成这样:
I think your code would benefit from some rearrangement. I'd structure it something like this:
您得到的输出是因为您的循环在非负数处失败。您应该尝试以下操作:
The output you are getting is because your loop fails at non-negative numbers. You should try the following:
据我了解,如果数字为负数,则您希望接受另一个输入。但 cin 语句不受循环控制来执行此操作。无论数字的性质如何,它都只执行一次。
From my understanding, if the number is negative, you wish to take another input. But the
cin
statement is not under loop control to do it so. It just executes only one time irrespective of the nature of the number.