我已经学习了3个月的c ++,并且我研究了数组,我编写了一个程序,它将从用户那里获取输入,然后程序将这些数字存储在一个特殊的数组中,然后程序将它们分成两个数组,一个用于偶数,另一个用于奇数,我的问题是,当我试图显示它们时,发生了一些错误,但我无法弄清楚,你能帮帮我吗?
int main () {
int even[5];
int odd[5];
int num;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[i] += num;
}
else{
cout << "its an odd number!";
odd[i] += num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u<4; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<4; z++){
cout << even[z] << endl;
}
}
感谢您帮助我!
答案 0 :(得分:2)
从您的问题来看,您似乎正在尝试将给定的整数数组拆分为两个数组甚至奇数。这里的问题是您将值分配到新数组的方式,您有一个计数器i
,负责将值放入even[i]
和odd[i]
。所以你有很多破碎的部分甚至[0]可能存在,但奇数[1]可能是你获得的第一个奇数值。您应该有单独的计数器来存储这些值。因此,对代码的更正将如下所示
int main () {
int even[5];
int odd[5];
int num;
int evencount = 0;
int oddcount = 0;
cout << "enter 4 numbers!";
for(int i=0; i<4; i++) {
cin >> num;
if( num%2 == 0){
cout << "its an even number!";
even[evencount++] = num;
}
else{
cout << "its an odd number!";
odd[oddcount++] = num;
}
}
cout << "The odd number/s is/are: ";
for( int u=0; u < oddcount; u++){
cout << odd[u] << endl;
}
cout << endl;
cout << "The even number/s is/are: " << endl;
for(int z=0; z<evencount; z++){
cout << even[z] << endl;
}
}
答案 1 :(得分:0)
我的方法略有不同:
#include <iostream>
using namespace std;
int main () {
int array[4]; // array size needs to be 4 only and not 5
/*int num;*/ // not required
bool is_odd[4] = {false, false, false, false};
cout << "enter 4 numbers!\n";
for(int i=0; i<4; i++) {
cin >> array[i];
if( array[i]%2 == 0){
cout << "its an even number!\n";
}
else{
cout << "its an odd number!\n";
is_odd[i] = true;
}
}
cout << "The odd number/s is/are:\n";
for( int u=0; u < 4; u++){
if (is_odd[u] == true)
cout << array[u] << endl;
}
cout << endl;
cout << "The even number/s is/are:\n" << endl;
for(int u=0; u < 4; u++) {
if (is_odd[u] == false)
cout << array[u] << endl;
}
}
在此处查看答案:check-answer
答案 2 :(得分:0)
您可以访问已声明但未初始化的数组值。所以它里面有任何价值。像6.49e154。声明时始终初始化!