2015-03-17 2 views
0

Я изучаю C в течение нескольких дней, и когда я использую Printf для преобразования температур, он отображает неправильный вывод.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; 
} 
} 
+0

В дополнение к приведенному ниже ответу и комментариям используйте 'float temp;' и 'scanf ("% f ", &temp);'. – DigitalNinja

+0

user3121023 спасибо. У меня была более ранняя версия со строками вместо "chars" и забыл изменить мой синтаксис –

+0

«Он отображает неправильный вывод» не является полезным описанием проблемы. Какой результат вы получаете? Как вы думаете, что с этим не так? –

ответ

0
scanf("%s", &temp); 

Формат %s спецификатор для строк. Вы читаете целое число, поэтому вы хотите %d.

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; 
} 
Смежные вопросы