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

C语言程序中如何结合使用function与switch实现温度单位转换功能

C语言温度转换程序问题修正

现有代码问题汇总

  • 逻辑顺序错误:switch分支被放在do-while菜单循环外部,仅当用户选择退出选项3时才会执行一次分支判断,选择转换选项1、2时完全不会触发计算输出逻辑
  • 命名冲突:main函数中定义的局部变量F、C与你之前定义的温度转换函数同名,会覆盖函数定义,导致无法正常调用转换函数
  • 循环条件错误:两个转换函数中的for循环判断条件写为赋值语句a = size,会触发死循环,正确判断逻辑应为a < size
  • 整数除法精度问题:C语言中整数运算9/5结果为1、5/9结果为0,完全无法得到正确的温度转换结果,需要改为浮点数运算
  • 函数调用语法错误:F = (input, SIZE)属于逗号表达式写法,并未实际调用转换函数,正确调用格式为F(input, SIZE)
  • 冗余无效代码:转换函数中if (input[a] = result);为无效空语句,无任何作用可直接删除
  • 输入时机错误:现有代码进入菜单前就要求用户输入温度,不符合使用逻辑,应该在用户选中对应转换选项后,再提示用户输入对应单位的温度值

修正后完整代码

#include <stdio.h>
#include <stdlib.h>
#define SIZE 1

// 获取用户输入的温度值
int getValue() {
    int result;
    printf("Input degree: ");
    scanf_s("%i", &result);
    return result;
}

// 摄氏度转华氏度:F = (9.0 / 5.0) * C + 32
int CtoF(int input[], int size) {
    int result = 0;
    for (int a = 0; a < size; a++) {
        result = (9.0 / 5.0) * input[a] + 32;
    }
    return result;
}

// 华氏度转摄氏度:C = (5.0 / 9.0) * (F - 32)
int FtoC(int input[], int size) {
    int result = 0;
    for (int a = 0; a < size; a++) {
        result = (5.0 / 9.0) * (input[a] - 32);
    }
    return result;
}

int main() {
    int choice;
    int input[SIZE];
    int convertRes;

    do {
        printf("\nWelcome to the Main Menu\n");
        printf("1. Convert temperature input from the user in degrees Fahrenheit to degrees Celsius\n");
        printf("2. Convert temperature input from the user in degrees Celsius to degrees Fahrenheit\n");
        printf("3. Quit.\n");
        scanf_s("%i", &choice);

        // switch分支放在循环内部,选中选项后立即执行
        switch (choice) {
            case 1:
                input[0] = getValue();
                convertRes = FtoC(input, SIZE);
                printf("%i degree C\n", convertRes);
                break;
            case 2:
                input[0] = getValue();
                convertRes = CtoF(input, SIZE);
                printf("%i degree F\n", convertRes);
                break;
            case 3:
                printf("You have chosen option 3 you are now able to quit\n");
                break;
            default:
                printf("Invalid option, please try again\n");
        }
    } while (choice != 3);

    system("pause");
    return 0;
}

内容的提问来源于stack exchange,提问作者Moon chick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:05