我是初学者,我不明白错误是什么。你能帮女孩吗?



创建并打印两个实数X(N(、Y(M((小数点后S位(的源数组。定义一个包含较少负元素的数组。使用函数:用随机数初始化,输出,确定任意整数数组中负元素的数量。C++编译很好,但显示一个错误";分段故障(堆芯倾倒(";

在此处输入代码

#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <math.h>
#include <time.h>
using namespace std;
const int S=2;
void init(double a[], int n, double b[], int m) {
int c=0, k=0;
srand(time(0));
cout<<"Enter the number of elements in the array X:";
cin>>n;
cout<<"Array X is:";
for(int i=0; i<n;i++) {
a[i]=rand()%50-100/3.;
cout.precision(S);  
cout<<setw(8)<<fixed<<a[i]<<" ";
}

for (int i=0; i<n; i++)
if (a[i]<0) c++;

cout<<endl;
cout<<"Enter the number of elements in the array Y:";
cin>>m;
cout<<"Array Y is:";
for(int i=0; i<m;i++) {
b[i]=rand()%50-100/7.;
cout.precision(S);
cout<<setw(8)<<fixed<<b[i]<<" ";
}

for (int i=0; i<m; i++)
if (b[i]<0) k++;
cout<<endl;

cout<<"Total negative elements in the array X: "<<c<<"."<<endl;
cout<<"Total negative elements in the array Y: "<<k<<"."<<endl;

if(c>k)
cout<<"Array X has more negative elements than array Y."<<endl;
else if (c<k)
cout<<"Array Y has more negative elements than array X."<<endl;
else 
cout<<"Array X and array Y have the same number of negative elements."<<endl;

}
int main() {
int N, M;
double X[N],Y[M];
init(X,N,Y,M);

return 0;
}

在C++中,不能声明具有从输入读取的大小的数组。您尤其不能用稍后从输入中读取的大小来声明它。

如果您想要一个动态大小的数组,请使用std::vector

#include <iostream>
#include <vector>
#include <math.h>
#include <time.h>
void init() {
srand(time(0));
std::cout<<"Enter the number of elements in the array X:";
std::size_t n
std::cin >> n;
std::vector<double> a(n);
std::cout<<"Array X is:";
for(int i=0; i<n;i++) {
a[i]=rand()%50-100/3.;
cout.precision(S);  
std::cout<<setw(8)<<fixed<<a[i]<<" ";
}

int c = 0;
for (int i=0; i<n; i++)
if (a[i]<0) c++;

std::cout<<std::endl;
std::cout<<"Enter the number of elements in the array Y:";
std::size_t m;
std::cin>>m;
std::vector<double> b(m);
std::cout<<"Array Y is:";
for(int i=0; i<m;i++) {
b[i]=rand()%50-100/7.;
cout.precision(S);
std::cout<<setw(8)<<fixed<<b[i]<<" ";
}
int k = 0;        
for (int i=0; i<m; i++)
if (b[i]<0) k++;
std::cout<<endl;

std::cout<<"Total negative elements in the array X: "<<c<<"."<<std::endl;
std::cout<<"Total negative elements in the array Y: "<<k<<"."<<std::endl;

if(c>k)
std::cout<<"Array X has more negative elements than array Y."<<std::endl;
else if (c<k)
std::cout<<"Array Y has more negative elements than array X."<<std::endl;
else 
std::cout<<"Array X and array Y have the same number of negative elements."<<std::endl;

}
int main() {
init();
return 0;
}

using namespace std是个坏习惯。如果你的老师告诉你使用它,他们错了。

std::uniform_real_distribution与来自<random>的生成器一起来看,以生成两个极限之间的随机二重。

看看std::count_if和函数bool isNegative(double x) { return x < 0 },计算有多少数字是负数。

最新更新