我不知道为什么程序无法给出输出,这是查找零个数的代码 在给定的数组中
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int b=0 , a;
for(int j=0; j<n; j++)
{
a=arr[j];
while(a==0)
{
b=b++;
}
}
cout<<b;
}
只需在 j for 循环中执行此操作即可。你不需要任何
a
变量或任何东西
C++ 中也不允许运行时变量数组使用动态数组或
vectors
for(int j=0; j<n; j++)
{
if(arr[j]==0){
b++;
}
}
尝试将其更改为
if (a==0) //you had a while here
{
b++;
}
由于您没有在循环内更改“a”的值,因此它会卡在 while 内,从而导致无限循环!
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int b = 0, a = 0;
for (int j = 0; j < n; j++)
{
a = arr[j];
if (a == 0) //here you used while use if as you are checking the condition every iteration of loop.
{
b++;
}
}
cout << b;
return 0;
}