[英]enter Odd, Even, zero and negative numbers and count using for and while loop in C++ without using arrray
我在编程过程中遇到了一些问题。 我想编写一个程序来使用while和for循环来区分偶数、奇数、零值和负数。 第一个问题:但是,当我尝试运行我的程序时,我输入的最后一个数字不会被计算在内。 我知道这是因为我的 o++ 放在 if 条件的顶部,我应该如何解决我的问题? 第二个问题:对于for循环部分,实际上它可能会忽略那些负值。 我应该如何解决它以让负数也计入循环? 我可以将 num>0 更改为 num < 100000 以让 for 循环工作吗?
#include<iostream>
using namespace std;
#include<iostream>
using namespace std;
int main ()
{
int num ,numbers = 1 ;
char answer = 'Y' ;
int o=0, e=0, z=0 ,n=0 ;
// o for odd numbers, e for even numbers, z for zero values, n for negative numbers
cout << "Enter number" << numbers << ": " << endl ;
cin >> num ;
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
{
if (num % 2 == 0 && num > 0)
{
e++ ;
cout<< "The number of even numbers is :" << e << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num ;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num % 2 == 1 && num > 0)
{
o++;
cout<< "The number of odd numbers is :" << o << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
else if (num == 0)
{
z ++;
cout<< "The total of 0 is :" << z << endl;
numbers ++ ;
cout<<"Please enter number" << numbers << endl ;
cin >> num;
cout<<"If you wish to continue, Please enter y or Y to continue this program : "<< endl ;
cin>> answer ;
}
}
cout << "The total even numbers is :" << e << endl;
cout << "The total odd numbers is :" << o << endl ;
cout << "The total negative numbers is :" << n << endl ;
cout << "The total zero number is:" << z << endl;
return 0;
}
main() 中的这一行真的很令人费解:
// ...
for ( num = num ; num >0; num++)
while (answer == 'y' || answer == 'Y')
for(;;) 语句是您的主循环。 只要 num 为正数,while 语句就会被执行。
让我们详细看一下这个 for() 语句:
for (num = num; // num = num ??? this statement does nothing.
num > 0; // the while statement (and the contents of the whule() loop block)
// will only execute if num is > 0.
++num) // if num was > 0 then this loop will run until num overflows...
删除 for(;;) 语句将使您的程序运行得更好。
你的o++
与它无关。
(也许您已经非常确信这是您没有想到其他地方的问题。它发生在每个人身上。)
问题是你的序列是这样的:
而且,如果用户不想继续,您会停止计数,最后一个数字似乎已经消失了。 将其修复为练习。
(更仔细地考虑你需要按哪个顺序做事。)
处理负数需要您编写一些代码来执行此操作 - 您处理两种正数情况,一种情况为零,但您一定忘记了负数。
解决这个问题也留作练习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.