Printf产生错误的整数

时间:2015-03-17 23:59:12

标签: c printf

我已经学习了几天C,当我使用Printf来转换温度时,它会显示错误的输出。

int main() {
    char sys;
    int temp;
    printf("Enter a tempature system [c or f]: ");
    scanf("%c", &sys);
    printf("Enter a tempature: ");
    scanf("%s", &temp);
    if (sys == 'f') {
    int output = (temp - 32) * 5/9;
    printf("%d Fahrenheit is %d Celsius\n",temp,output);
    return 0;
}
    else if (sys == 'c') {
    int output = temp * 9/5 + 32;
    printf("%d Celsius is %d Fahrenheit\n",temp,output);
    return 0;
 }
}

2 个答案:

答案 0 :(得分:1)

#include <stdio.h>

int main() {
    char sys;
    float temp,output;

    printf("Enter a tempature system [c or f]: ");
    scanf("%c", &sys);

    printf("Enter a tempature: ");
    scanf("%f", &temp);

    if (sys == 'f') {
        output = (temp - 32.0) * (5.0 / 9.0);
        printf("%.2f Fahrenheit is %.2f Celsius\n",temp,output);
    }
    else if (sys == 'c') {
        output = (temp * 9.0 / 5.0) + 32.0;
        printf("%.2f Celsius is %.2f Fahrenheit\n",temp,output);
    }

    return 0;
}

答案 1 :(得分:0)

scanf("%s", &temp);

%s格式说明符用于字符串。你正在读一个整数,所以你需要%d