实现两点间距离计算时的变量输出异常问题求助
修正后的两点间距离计算代码
原代码问题分析
- 输入提示的
printf语句错误添加了%d %d占位符,输出了未初始化变量的随机值 - 未引入
math.h头文件,sqrt函数无法正常编译 - 用
int类型存储平方根结果,会丢失小数精度 - 输出时用
%d格式化浮点数值,格式不匹配导致结果异常
修正后的代码
#include <stdio.h> #include <math.h> // 引入sqrt函数所需头文件 int main() { int x1, x2, y1, y2; // 修正提示语句,移除多余占位符 printf("Enter the value of x1 and y1: "); scanf("%d %d", &x1, &y1); printf("Enter the value of x2 and y2: "); scanf("%d %d", &x2, &y2); // 改用double类型计算,保留小数精度 double dx = x2 - x1; double dy = y2 - y1; double distance = sqrt(dx*dx + dy*dy); // 用浮点格式输出,保留两位小数提升可读性 printf("The length between the points = %.2f\n", distance); return 0; }
关键修改说明
- 删除输入提示
printf中的%d %d占位符,避免输出未初始化变量的随机值 - 添加
#include <math.h>,确保sqrt函数能正常编译 - 将距离计算相关变量改为
double类型,避免整数截断丢失精度 - 输出时使用
%.2f格式化浮点结果,保证格式正确且结果直观
内容的提问来源于stack exchange,提问作者Shubham Prakash
相关产品推荐
相关产品推荐

