【发布时间】:2021-06-05 20:03:45
【问题描述】:
我正在努力完成我的作业,但我在重复元素项目中遇到了一些问题。我试图找出问题出在哪里,但我找不到。我的代码在序列很小的时候可以正常工作,但是当序列很大时就会出现问题。
在这个序列中,我期望得到图片中的数字,但我总是得到第二张图片中的数字。可以看到,重复元素中的这一项总是有问题。
#include <iostream>
using namespace std;
int main()
{
int count = 0;
int arrayA[25];
int arrayB[25];
int min,max;
int num;
int i = 0;
int n = 0;
int temp = 0;
int sum = 0;
//Input
cout << "Input the number of elements to store in the array: ";
cin >> n;
cout << n << endl;
cout << "Input "<< n <<" integers:" << endl;
//Store arrayA
if(count < n){
for(i = 0; i < n; i++){
cin >> num;
cout << "integer - " << count;
cout << " : " << num <<endl;
arrayA[count] = num;
count++;
}
}
//store arrayB
for(i = 0;i < count; i++){
arrayB[i] = arrayA[count - i - 1];
}
//Forwards Array
cout << "The values stored into the array are :" << endl;
for(i = 0;i < count; i++){
cout << arrayA[i] << " ";
}
cout << endl;
//Backwards Array
cout << "The values stored into the array in reverse are :" << endl;
for(i = 0; i < count; i++){
cout << arrayB[i] <<" ";
}
cout << endl;
//Sum
for(i = 0; i < count; i++){
sum += arrayA[i];
}
//Max & Min
for(i = 0; i < count;i++){
if(max < arrayA[i]){
max = arrayA[i];
}
}
for(i = 0; i < count; i++){
if(min > arrayA[i]){
min = arrayA[i];
}
if(arrayA[i]== 0){
min = 0;
break;
}
}
//Duplicate elements
count = 0;
for(i = 0; i < n; i++){
for(temp = i + 1; temp < n; temp++){
if(arrayA[i] == arrayA[temp] ){
count++;
break;
}
}
}
cout << "The sum of all elements of the array is ";
cout << " " << sum << endl;
cout << "The total number of duplicate elements in the array is ";
cout << count << endl;
cout << "The maximum and minimum element in the array are ";
cout << min << " , " << max;
return 0;
}
【问题讨论】:
-
您的输出应该包含为文本,而不是图像。您是否考虑过如果一个数字出现两次以上会发生什么(例如您的示例中的“4”)?
-
在计数时打印您要比较的项目,一个简单的调试步骤,就会给您很多洞察力。