#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
int num,i,b;
printf("请输入一个数字:\n");
scanf("%d",&num);
for(i=0;i<=10;i++)
{
b=((num=a[i])?1:2);
if(b==1)
{
printf("%d在数组中\n",num);
}
else if(b==2)
{
printf("%d不在数组中\n",num);
}
}
return 0;
}
最好自己有初步的分析,以及谁告诉你代码有错,有什么错误现象
第14行循环应该是i<10,不能i<=10
i=10时会数组越界访问
题目:判断一个数是否在数组中?
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
int num,i,b=2;
printf("请输入一个数字:\n");
scanf("%d",&num);
for(i=0;i<10;i++)
{
if(num==a[i]){
b=1;
break;
}
}
if(b==1)
{
printf("%d在数组中\n",num);
}
else if(b==2)
{
printf("%d不在数组中\n",num);
}
return 0;
}
没报错啊,你认为哪里有问题?
b=((num==a[i])?1:2);
赋值写错了,要 == 不是 =