【发布时间】:2021-05-04 15:48:13
【问题描述】:
所以我试图让我的偶数出现并告诉我用户输入的结果。不知道为什么我的函数在我的 main 中出现错误,当我试图让它在我的 even 函数中输出时不会打印。不确定为什么?也很好奇我应该锁定并使我的数组保持不变吗?它没有改变,但我可能觉得我必须让它保持不变并锁定它,以防我必须改变一些东西来检查偶数。另外,我是初学者,几乎不了解数组。
#include <iostream>
#include <string>
using namespace std;
// putting our voids first to declare be declare and run first
void fillUp(int num[], int size)
{
//user input
cout<<"Enter "<<size<<" and then press the ENTER/RETRUN: ";
for(int i = 0; i < size; i++)
{
cin>> num[i];
}
}
//obtaining user input and totaling them up
int total(int num[], int size)
{
int total = 0;
for(int i = 0; i < size;i++)
{
total += num[i];
}
return total;
}
int EvenElements(int num[], int size, int& evenCounter)
{
for(int i = 0; i<size;i++)
{
if(num[i] % 2 == 0)
{
evenCounter++;
}
}
return(evenCounter);
}
//display the array in a row
void display(int num[], int size)
{
for(int i = 0; i<size;i++)
{
cout<<num[i]<<" ";
}
}
//main function to display the results of the user input
int main()
{
int numOne[4], numTwo[5], numThree[6], evenCounter;
fillUp(numOne, 4);
fillUp(numTwo, 5);
fillUp(numThree, 6);
cout<<"The numbers in the array are: ";
display(numOne, 4);
cout<<" and the total of these numbers is "<<total(numOne, 4)
<<endl;
cout<<"The numbers in the array are: ";
display(numTwo, 5);
cout<<" and the total of these numbers is "<<total(numTwo, 5)
<<endl;
cout<<"The numbers in the array are: ";
display(numThree, 6);
cout<<" and the total of these numbers is "<<total(numThree, 6)
<<endl;
cout<<"This is how many evens were in the array: ";
EvenElements(evenCounter);
}
【问题讨论】:
-
给定的代码无法编译。
EvenElements(evenCounter);不能用来调用int EvenElements(int num[], int size, int& evenCounter)确保你在调试时没有破坏它。 -
在上面的代码中你也没有给
evenCounter一个值。你在函数EvenElements中增加它,但它没有给出初始值。大概应该给它一个初始值为零。 -
在上面的代码中你也没有打印
evenCounter的值。 -
我明白了,我将计数器值设置为现在,现在它出现并显示为 0,到目前为止非常好,我认为我绝对应该使用调试功能来查看我是否没有破坏它。跨度>
标签: c++ arrays function counter