You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现两点间距离计算时的变量输出异常问题求助

修正后的两点间距离计算代码

原代码问题分析

  1. 输入提示的printf语句错误添加了%d %d占位符,输出了未初始化变量的随机值
  2. 未引入math.h头文件,sqrt函数无法正常编译
  3. 用int类型存储平方根结果,会丢失小数精度
  4. 输出时用%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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:55:26