最近几天我的代码出现了一个大问题。虽然scanf()函数在我的编程过程中似乎工作得很好,但当程序到达某个点时(我扫描一个浮点数),我只是在变量min_dist中输入我想要保存的值,但当我打印它之后,变量有一个完全不同的值,因此整个程序都一团糟。我使用的是Code::Blocks提供的免费编译器,这可能是个问题吗?我的朋友在他的电脑里编译了同样的程序,没有出现任何问题!这是我的代码:
#include <stdio.h>
#include <math.h>
void main() {
int codeA[50],codeB[50],over[2500][2],numA,numB,min_dist;
int i,j,k=0 ;
float xA[50],yA[50],zA[50],xB[50],yB[50],zB[50] ;
double sq_dist,dist ;
printf("Enter the number of spots for company A: n");
scanf("%d",&numA);
printf("Enter the number of spots for company B: n");
scanf("%d",&numB);
for (i=0; i<numA; i++) {
printf("Enter code of company A's spot number %d n",i+1) ;
scanf("%d",&codeA[i]) ;
printf("Enter spot's coordinates: n");
printf("On axis X: n") ;
scanf("%f",&xA[i]);
printf("On axis Y: n");
scanf("%f",&yA[i]);
printf("On axis Z: n");
scanf("%f",&zA[i]);
}
for (i=0; i<numB; i++) {
printf("Enter code of company B's spot number %d n",i+1) ;
scanf("%d",&codeB[i]) ;
printf("Enter spot's coordinates: n");
printf("On axis X: n") ;
scanf("%f",&xB[i]);
printf("On axis Y: n");
scanf("%f",&yB[i]);
printf("On axis Z: n");
scanf("%f",&zB[i]);
}
printf("Enter the minimum distance between 2 spots n");
****scanf("%d",&min_dist);
printf("%d",min_dist);****
for (i=0; i<numA; i++) {
for (j=0; j<numB; j++) {
sq_dist=(xA[i]-xB[j])*(xA[i]-xB[j]) + (yA[i]-yB[j])*(yA[i]-yB[j]) + (zA[i]-zB[j])*(zA[i]-zB[j]) ;
dist=sqrt(sq_dist);
printf("%f n",dist);
if (dist<=2) {
over[k][0]=codeA[i];
over[k][1]=codeB[j];
k++ ;
}
}
}
printf("%d, %f n",k,dist);
printf("These spots collide: n");
for (i=0; i<k; i++){
printf("code A: %d code B:%d n",over[i][0],over[i][1]);
}
for (i=0; i<numA; i++) {
for (j=0; j<k; j++) {
if (codeA[i]==over[j][0]) {
codeA[i]=0 ;
xA[i]=0;
yA[i]=0;
zA[i]=0;
continue ;
}
}
}
for (i=0; i<numB; i++) {
for (j=0; j<k; j++) {
if (codeB[i]==over[j][1]) {
codeB[i]=0 ;
xB[i]=0;
yB[i]=0;
zB[i]=0;
continue ;
}
}
}
for (i=0; i<numA; i++) {
if (codeA[i]!=0) {
printf("Remaining company A's spot code %d n",codeA[i]) ;
printf("Coordinates x,y,z: n %f,%f,%f n",xA[i],yA[i],zA[i]) ;
}
}
for (i=0; i<numB; i++) {
if (codeB[i]!=0) {
printf("Remaining company B's spot code %d n",codeB[i]) ;
printf("Coordinates x,y,z: n %f,%f,%f n",xB[i],yB[i],zB[i]) ;
}
}
}
事实上,我会得到不同的错误结果,这取决于我键入的内容。例如:当我键入2作为最小距离时,数字21.715021会直接打印在后面。如果我输入10,101.705021(或者类似的东西记不清了)会直接打印在后面。如果我将min_dist声明为float,则会直接在后面打印一个数字,如1.025846e-210。
我强调了出现问题的程序点。我是c的新手,也不是以英语为母语的人,所以请原谅我的语法错误。
您提到将浮点数读取到min_dist
中,但调用是:
scanf("%d",&min_dist);
这是在尝试将一个积分读入min_dist
。你是想用%f
吗?