目标:
- Program that reads a list of integers
- Outputs whether the list contains all even numbers, odd numbers, or neither
- Input begins with an integer indicating the number of integers that follow
- Contains less than 20 ints
我的代码可以输出偶数和奇数,执行我的else语句“不偶数或奇数”时遇到麻烦。我将代码放入Xcode,它说我的循环函数(偶数,奇数)有错误。我注释了每个for循环中的第一个返回值,并解决了该问题,但是当我将其放入我学校的程序中时,它除外。
我的代码:
#include <iostream>
using namespace std;
// proto
bool IsArrayEven(int inputVals[], int numVals);
bool IsArrayOdd(int inputVals[], int numVals);
int main() {
int MAX_ELEMENTS = 20;
cin >> MAX_ELEMENTS;
int userVals[MAX_ELEMENTS];
int i;
// populating array
for(i = 0;i < MAX_ELEMENTS; ++i){
cin >> userVals[i];
}
if(IsArrayEven(userVals, MAX_ELEMENTS)){
cout << "all even" << endl;
}else if(IsArrayOdd(userVals, MAX_ELEMENTS)){
cout << "all odd" << endl;
}else{
cout << "not even or odd" << endl;
}
return 0;
}
// function definition - EVENS
bool IsArrayEven(int inputVals[], int numVals){
for(int i = 0; i < numVals; ++i){
if(inputVals[i] % 2 != 0){
return false;
}
else {
return true;
}
}
return 0;
}
// function definition - ODDS
bool IsArrayOdd(int inputVals[], int numVals){
for(int i = 0; i < numVals; ++i){
if(inputVals[i] % 2 == 0){
return false;
}
else {
return true;
}
}
return 0;
}