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

C语言程序问题:无法输入华氏度,函数代码被跳过如何修复

问题修复方案

核心问题

  • ask_for_air_celcius函数中,第一个return语句会直接终止函数,导致后续的华氏度输入代码永远无法执行。
  • 两次调用同一函数,只能获取摄氏度,无法实现第二次输入华氏度的需求。

修复步骤

1. 拆分温度输入函数

将原函数拆分为两个独立函数,分别处理摄氏度和华氏度的输入:

#include <stdio.h>
#include <math.h>

// 获取摄氏度输入
double get_celcius()
{
    double temp;
    printf("Enter the current air temperature(in Celcius): ");
    scanf(" %lf", &temp);
    return temp;
}

// 获取华氏度输入
double get_fahrenheit()
{
    double temp;
    printf("Enter the current air temperature(in Fahrenheit): ");
    scanf(" %lf", &temp);
    return temp;
}

2. 调整main函数的调用逻辑

把第二次的函数调用替换为华氏度输入函数,同时保留原有的正确计算逻辑:

int main()
{
    double celcius, spsound_c, spsound_c_km, fahrenheit, spsound_f, spsound_f_km;

    celcius = get_celcius(); 
    spsound_c = 1086 * sqrt(((5 * (celcius*1.8+32)) + 297) / 247);
    spsound_c_km = spsound_c * 1.09728;
    
    fahrenheit = get_fahrenheit(); 
    spsound_f = 1086 * sqrt(((5 * fahrenheit) + 297) / 247);
    spsound_f_km = spsound_f * 1.09728;
    
    printf("\nThe speed of sound at %.2f degrees Celcius is %.2f ft/s.\n", celcius, spsound_c);
    printf("The speed of sound at this temperature in Celcius is equivalent to %.2f km/h.\n\n", spsound_c_km);
    printf("The speed of sound at %.2f degrees Fahrenheit is %.2f ft/sec.\n", fahrenheit, spsound_f);
    printf("The speed of sound at this temperature in Fahrenheit is equivalent to %.2f km/h.\n", spsound_f_km);
    
    return 0;
}

修复说明

  • 拆分函数后,两个输入逻辑互不干扰,不会出现代码被跳过的情况。
  • 优化了变量命名,让代码更易读,避免歧义。
  • 完全保留了你原本正确的计算逻辑和输出格式,仅调整了输入部分的调用逻辑。

内容的提问来源于stack exchange,提问作者Daniel Avella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:10:16