所以我正在尝试制作一个程序,将一个int数组分成两个,一个用于偶数,一个用于不均匀的int。现在,奇怪的是,如果我只输入偶数或不均匀的数字到基数组,程序工作正常,但如果我输入两者的混合,两个新数组保持的值之一将是随机的,通常是消极的,大数字,任何想法为什么会这样?
#include <iostream>
using namespace std;
void main()
{
int *a, n, *even_nums = 0, *uneven_nums = 0, counter_even = 0,counter_uneven = 0;
cout << "How many values does your array have?\n" << endl;
cin >> n;
a = new int[n];
cout << "\nEnter the values in your array:" << endl;
for (int i = 0; i < n; i++)
{
cout << "a[" << i << "] = ";
cin >> a[i];
if (a[i] % 2 == 0)
counter_even++;
else
counter_uneven++;
}
if (counter_even == 0)
cout << "There are no even numbers in your array." << endl;
else
even_nums = new int[counter_even];
if (counter_uneven == 0)
cout << "There are no uneven numbers in your array." << endl;
else
uneven_nums = new int[counter_uneven];
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
if (counter_even != 0)
{
cout << "\nThe even numbers in your array are:" << endl;
for (int i = 0; i < counter_even; i++)
cout << even_nums[i] << " ";
}
if (counter_uneven != 0)
{
cout << "\nThe uneven numbers in your array are:" << endl;
for (int i = 0; i < counter_uneven; i++)
cout << uneven_nums[i] << " ";
}
system("PAUSE");
}
答案 0 :(得分:0)
在块中
i
您使用a
作为数组even_nums
,uneven_nums
和even_nums
的相同索引。您需要为这些数组使用单独的索引。
例如,如果您有n = 10个元素,5个偶数和5个奇数,则uneven_nums
和$scope.favorites = ["a", "b", "c", "d"];
$scope.dataCount = 4;
$scope.$watchCollection('favorites', function(newFavs, oldFavs) {
$scope.dataCount = newFavs.length;
});
每个只包含5个元素。
答案 1 :(得分:0)
在
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
您对所有阵列使用相同的索引。如果您同时使用even_nums
,uneven_nums
将小于a
,则此功能无效。您将最终写入数组末尾undefined behavior。
您需要做的是为每个数组添加一个索引,每次将元素插入数组时,都会推进该索引。
for (int i = 0, u = 0, e = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[e++] = a[i];
else
uneven_nums[u++] = a[i];
}
此外,您使用的是void main()
,这不是标准的,不应使用。 int main()
和int main(int argc, char** argv)
是main()