C语言double型数据比较大小出错。

#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;

}

这样就没错了。

运行结果:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-21
if(b==a[(i+n)/2]) // b 是double类型,a[i] 会被隐式的转换成double类型,
而,double 类型是不能直接用“==”比大小的。因为double类型或float类型都是有精度的,其实都是取的近似值,所以有个误差。
if(b-a[(i+n)/2]<1e-8) // 只要相减的值在你规定的大小范围内就可以认为是相等的。
第2个回答  2012-12-21
都是同样的错误, 'double *' to 'double'
假设 doube a = 2.1; double b = &a; 这样就是错的,因为b是a的指针,而不是a的值
对照程序改一下吧,不懂的继续追问
第3个回答  2012-12-21
int main()
{
int a[15]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15},i,n,b,k;

你在main前不要定义数据类型,在{ } 里定义数组为float,i,n,b,k定义为int 就可以了。。
最后printf输出的时候,要记得把输出改成%.1f。。。
相似回答