【发布时间】:2021-09-09 14:55:13
【问题描述】:
这是一个 C++ 程序,用于搜索数字并在数组中找到时显示其索引位置。
程序运行良好。我只是想问为什么我们在 if 语句中使用 k=1 因为如果我们不使用它,那么程序将无法运行。请解释一下 if 语句中第二个 for 循环中 k=1 的意义。
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Size of Array: ";
cin>>n;
int arr[n];
cout<<"Type Elements of Array: ";
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
int k;
cout<<"Enter No to be found: ";
cin>>k;
for(int i=0; i<n; i++)
{
if(arr[i]==k)
{
k=1;
cout<<"No is found at index position: "<<i<<endl;;
break;
}
else
{
cout<<"No is not found";
break;
}
}
return 0;
}
【问题讨论】:
-
该程序将无法运行无论该行是否在其中。
-
“程序运行良好。” - 不,它根本无法运行。它只会检查第一个数字并跳出循环。更不用说
int arr[n];是非标准 C++ 并且不能在所有编译器上工作。
标签: c++ arrays for-loop if-statement