随机整数出现在程序错误
Random Integers Appearing In Program Bug
所以我试着编写一个程序,将一个整型数组分成两个,一个用于偶数整型,一个用于非偶数整型。现在,奇怪的是,如果我只在基本数组中输入偶数或非偶数,程序运行正常,但如果我输入两者的混合,两个新数组中保存的一个值将是一个随机的,通常是负数,大数,知道为什么吗?
#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");
}
In
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
,如果你有两个。你最终会写过数组的末尾,这是未定义的行为。
你需要做的是为每个数组添加一个索引,并且每次你向数组中插入一个元素时,你就会推进该索引。
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()
的标准可接受签名
for (int i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
even_nums[i] = a[i];
else
uneven_nums[i] = a[i];
}
您正在使用i
作为数组a
, even_nums
和uneven_nums
的相同索引。您需要为这些数组使用单独的索引。例如,如果您有n=10个元素,5个偶数和5个奇数,您的even_nums
和uneven_nums
每个只包含5个元素。
相关文章:
- C++程序错误:malloc():内存损坏
- C++ Windows 凭据提供程序错误屏幕
- 程序错误地读取了二进制文件的一个字节
- Cmake无法在qt-creater/collect2上编译简单的测试程序:错误:ld
- C 程序错误
- SDL 应用程序错误:“if”之前应为非限定 id
- C++程序错误
- Apache IGNITE编译ODBC驱动程序错误
- 二进制搜索树操作程序错误:分割故障(核心倾倒)
- Cygwin1.dll c++ 应用程序错误
- 无法编译任何C++程序;错误:未知类型名称'uint8_t'
- 带有结构和指针的程序错误(结构,C++)
- 矩阵运算C++运算符重载程序错误
- ilmerge后C /CLI应用程序错误
- SDL 2.0-无效的呈现程序错误
- 如何使用 C# 在网页 asp.net 显示 C 程序错误
- OPENCV:image_proc中的 PCA 应用程序错误
- C++程序错误 - 虚拟析构函数
- LNK2020 C 程序错误
- 程序错误,由于在VS2010中使用std::unique_ptr