#include<stdio.h>
int main()
{
int a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},i,n,b,k;
printf("输入一个数\n");
scanf("%f",&b);
for( i=0,n=15,k=0;k<=3;k++)
{
if(b==a[(i+n)/2])
{printf("此数是数组中第%d个数\n",(i+n)/2+1);break;
}
else if(b>a[(i+n)/2])
i=(i+n)/2;
else if(b<a[(i+n)/2])
n=(i+n)/2;
}
if(k==4)
printf("此数不在数组中\n");
return 0;
}
这是代码。
用的是折半法,找出输入的数是否是数组中的某个数。
用int整型没出错,改成DOUBLE型就出错了。
不知道为什么。
哪位大神搭救下
E:\C\qwe\asd.cpp(11) : error C2108: subscript is not of integral type
E:\C\qwe\asd.cpp(11) : error C2446: '==' : no conversion from 'double *' to 'double'
There is no context in which this conversion is possible
E:\C\qwe\asd.cpp(11) : error C2115: '==' : incompatible types
E:\C\qwe\asd.cpp(14) : error C2108: subscript is not of integral type
E:\C\qwe\asd.cpp(14) : error C2446: '>' : no conversion from 'double *' to 'double'
There is no context in which this conversion is possible
E:\C\qwe\asd.cpp(14) : error C2115: '>' : incompatible types
E:\C\qwe\asd.cpp(16) : error C2108: subscript is not of integral type
E:\C\qwe\asd.cpp(16) : error C2446: '<' : no conversion from 'double *' to 'double'
There is no context in which this conversion is possible
E:\C\qwe\asd.cpp(16) : error C2115: '<' : incompatible types
执行 cl.exe 时出错.
qwe.exe - 1 error(s), 0 warning(s)
楼主你好。
你犯懒了,你直接把int改成double了吧,如:
double a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},i,n,b,k;
【注意】后面的i,n,k应该是int类型的。
#include<stdio.h>
int main(){
double a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},b;//a和b是double类型
int i,n,k;//其他的是int类型
printf("输入一个数\n");
scanf("%lf",&b);//这里是%lf
for(i=0,n=15,k=0;k<=3;k++){
if(b==a[(i+n)/2]){
printf("此数是数组中第%d个数\n",(i+n)/2+1);break;
}
else if(b>a[(i+n)/2])
i=(i+n)/2;
else if(b<a[(i+n)/2])
n=(i+n)/2;
}
if(k==4)
printf("此数不在数组中\n");
return 0;
}
这样就没错了。
运行结果: