C++ 程序运行时没有错误,但给出了错误的结果

C++ 程序运行时没有错误,但给出了错误的结果,c++,C++,这段代码是数组中的一个练习 int L; int P=0; int N=0; int zero=0; cout<<"Enter The Size of Array : "<<" 'Note that it has to be bigger than 0'\n"; cin>>N; intl; int P=0; int N=0; int零=0; cout您似乎在使用变量N来计算数组的大小

这段代码是数组中的一个练习

int L;
int P=0;
int N=0;
int zero=0;
cout<<"Enter The Size of Array : "<<"                   'Note that it has to be bigger than 0'\n";
cin>>N;
intl;
int P=0;
int N=0;
int零=0;

cout您似乎在使用变量
N
来计算数组的大小和负数的数量。这很混乱,肯定会给你错误的结果


为数组大小创建一个额外变量。可以将其命名为
array\u size
或类似的名称,这样您就知道该值的含义了。

请注意。数组的长度必须是编译时常量,因为动态数组
std::vector
通常是最佳解决方案。您是否尝试过在调试器中逐行运行代码,同时监视所有变量的值,以确定程序在哪一点停止运行?如果未尝试此操作,则可能需要阅读以下内容:您可能还需要阅读以下内容:。问题是程序运行时没有出现错误,但它给出了错误的结果——这意味着程序运行时出现了错误。程序运行并不意味着你编写的代码是正确的。然后这个:
intz[N];int n=sizeof(z)/sizeof(z[0])既然<代码> int Z[n] < /C>不是标准C++,你怎么知道 siZoof < /Cord>技巧会起作用?
sizeof
是一个编译时常量,那么它如何在运行时知道
z[N]
的大小?忘记这一点,只需使用
std::vector
(如前所述)。那么大小就是向量的
size()
成员函数。计算大小是愚蠢的,它是显式输入的。
int z[N];
int n=sizeof(z)/sizeof(z[0]);
cout<<"The Number of elements in this array is : "<<n<<"\n";
for(int i=0;i<N;i++){
    cout<<"chose the "<<i<<" element : ";
    cin>>z[i];
}
for(int i=0;i<N;i++){
    if (z[i] > 0){
        P=P+1;
    }
    else if (z[i] < 0){
        N=N+1;
    }
    else{
            zero=zero+1;
    }

}
cout<<"The Number of Positive elements is : "<<P<<"\n";
cout<<"The Number of Negative elements is : "<<N<<"\n";
cout<<"The Number of zero elements is : "<<zero<<"\n";