#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1; counter <=LIMIT; counter++) {
cin>>number;
switch (number / 2) {
case 0: evens++;
if (number=0) zeros++;
case 1: case -1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
大家好,
我有一个校队问题让我整天难过。我需要修改上面的脚本,允许我输入10个变量整数,程序必须返回偶数的总数,奇数的总数和零的总数。
我尝试了多种解决方案,包括(编号%2 == 0),以便让我的案例在我的switch参数下运行,但是我遗漏了一些东西。
请有人协助我推动我走上正确的道路。
(我知道我需要删除否定的情况,但我想发布原始代码,因为我拿出一些东西或者修改一些需要的东西)
答案 0 :(得分:0)
#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
int n=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1;
counter <=LIMIT;
counter++) {
cin>>number;
n=(number%2);
switch (n) {
case 0: evens++;
if (number==0) zeros++;
break;
case 1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
感谢papagaga设法让它工作 - 我觉得我太累了:)。
答案 1 :(得分:0)
std::vector<int> myvec = {0, 2, 3, 5, 0, 0, 5, 4, 9};
std::vector<int> zeros;
std::vector<int> evens;
std::vector<int> odds;
for (auto i : myvec) {
if (i % 2 == 0) {
if (i == 0) zeros.push_back(i);
else evens.push_back(i);
}
else
odds.push_back(i);
}
std::cout << zeros.size();
std::cout << evens.size();
std::cout << odds.size();
return 0;
}
如果你不希望零在evens向量中,这将有效。