我正在尝试编写一个程序,要求用户输入整数序列。输入数字时,程序应计算奇数和偶数。用户输入完数据后,程序应显示输入的奇数和偶数。
我可以在不使用哨兵值的情况下实现上述结果吗? 另外,如果我问用户“您想输入多少个数字?”,如果输入为“ 5”,我如何让程序输出“输入数据:” 5次?
#include <iostream>
using namespace std;
int main()
{
int userInput;
int evenCount = 0;
int oddCount = 0;
cout << "Odd and Evens ";
do
{
cout << "Please enter an integer: ";
cin >> userInput;
if (userInput % 2 == 0)
{
evenCount++;
}
else
{
oddCount++;
}
} while (userInput != 0);
cout << "You entered " << oddCount << " odd numbers, and " << evenCount - 1 << " even numbers " << endl;
system("pause");
return 0;
}
这是我要通过程序实现的目标:
How many numbers are you going to enter? 5
Enter data: -5
Enter data: 2
Enter data: 3
Enter data: 6
Enter data: 0
Odd numbers entered: 2
Even numbers entered: 3
答案 0 :(得分:1)
首先提示用户要输入多少个数字。 输入该数字后,请循环使用,直到您的奇数和偶数总数小于该数字为止。
赞:
#include <iostream>
using namespace std;
int main()
{
int numberOfInput;
cout<<"How many numbers are you going to enter? ";
cin>>numberOfInput;
int userInput;
int evenCount = 0;
int oddCount = 0;
do
{
cout << "Enter data: ";
cin >> userInput;
if (userInput % 2 == 0)
{
evenCount++;
}
else
{
oddCount++;
}
}
while (evenCount+oddCount<numberOfInput);
cout<<"Odd numbers entered: "<<oddCount<<endl;
cout<<"Even numbers entered: "<<evenCount<<endl;
return 0;
}
答案 1 :(得分:1)
我将使用一个简单的for循环。
int main() {
int userinput;
int even=0;
int odd=0;
cout<<"Enter a value: ";
cin>>userinput;
int integerAdded;
for (int i=0;i<userinput;i++){
cout<<"Enter Data: ";
cin>>integerAdded;
if ((integerAdded%2)==0){
even++;
}
else{
odd++;
}
}
cout<<"The amount of even numbers is "<<even<<endl;
cout<<"The number of odd characters is: "<<odd<<endl;
}