标识符"n"未定义

identifier 'n' is undefined

本文关键字:未定义 标识符      更新时间:2023-10-16

这是我的代码

#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int array[100], beg, mid, end, i, num;
cout << "Enter the value of an array" << endl;
cin >> n;
cout << "Enter the values in sorted order (asc or desc)" << endl;
for (i = 0; i < n; i++)
{
cin >> array[i];
}
beg = 0;
end = n - 1;
cout << "Enter the value to searched in an array" << endl;
cin >> num;
while (beg <= end)
{
mid = (beg + end) / 2;
if (array[mid] == num)
{
cout << "Item found at this position" << (mid + 1);
exit(0);
}
else if (num > array[mid])
{
beg = mid + 1;
}
else if (num < array[mid])
end = mid - 1;
}
cout << "Number not found." << endl;
return 0;
}

我无法找到我的错误是什么。 它始终显示

标识符"n"未定义 "n":未声明的标识符

请任何人给我建议。提前谢谢。

一开始你必须声明变量:

int array[100], beg, mid, end, i, num, n;

N是唯一不声明但使用的变量。

错误引发,因为您在声明之前使用了变量n。所以首先像其他mid,num,i等一样声明变量n

更改您的声明行,如下所示

int array[100], beg, mid, end, i, num ,n; // declare n here before using
cout << "Enter the value of an array" << endl;
cin >> n;

n声明为int,您就可以开始了(仅适用于此错误):

int array[100], beg, mid, end, i, num, n;