C语言判断点与圆位置关系程序仅执行首条输入语句问题求解
错误排查&修复方案
1. 核心崩溃问题(直接导致程序无响应)
你代码中第一个scanf语句的第二个参数缺少取地址符&:
// 错误写法 scanf("%f%f%f",&f,g,&r); // 正确写法 scanf("%f%f%f",&f,&g,&r);
原因:
scanf要求传入接收输入值的变量内存地址,未加&时会把变量g的随机初始值当作内存地址写入,触发非法内存访问,直接导致程序崩溃/卡死,后续代码自然不会执行。
2. 其他可优化的潜在问题
- 浮点数相等判断逻辑错误:浮点数存在精度误差,直接用
==判断r和d相等会大概率出现误判,建议改为判断差值的绝对值小于极小阈值:// 原错误写法 if (r==d) // 优化写法 if (fabs(r - d) < 1e-6) - 距离计算写法优化:用标准库
sqrt计算平方根比pow(xxx, 0.5)性能更高、可读性更好:// 原写法 d=pow(pow((x-f),2)+pow((y-g),2),0.5); // 优化写法 d = sqrt((x-f)*(x-f) + (y-g)*(y-g)); - 输出缓冲区问题:
printf的提示信息末尾建议加换行符\n,避免行缓冲机制导致提示信息未及时打印到终端。
修复后完整可运行代码
//point wrt a circle #include <stdio.h> #include <math.h> int main(){ //input radius and centre float r,x,y,f,g,d; printf("Enter centre's x,y and radius: "); scanf("%f%f%f",&f,&g,&r); printf("enter the x y of the point:\n"); scanf("%f%f",&x,&y); //formula for distance d = sqrt((x-f)*(x-f) + (y-g)*(y-g)); //comparing d with r if (fabs(r - d) < 1e-6) printf("on the circle\n"); else if(r < d) printf("outside the circle\n"); else printf("Inside the circle\n"); return 0; }
内容的提问来源于stack exchange,提问作者Eyy boss
相关产品推荐
相关产品推荐

