C中的温度转换器程序不起作用。执行某些代码后停止(运行时错误)

问题描述 投票:-3回答:2

我写了一个C程序,将温度从华氏温度转换为细胞温度。它有三个函数,input_temp(),input_unit()和calculate()。想法很简单。 input_temp()要求用户输入温度值。 input_unit()要求用户输入单位,即F表示华氏度,C表示celcius。 Calculate()根据单位(celcius to fahrenheit或fahrenheit to celcius)转换温度。我使用Code :: Blocks作为我的IDE,但每当我尝试运行这个程序时,Code :: Blocks在询问数值温度单位后就会停止工作。当我尝试在ideone.com中运行相同的代码时,它表示运行时错误。这是代码:

#include <stdio.h>
#include <stdlib.h>

calculate(float T , char U[]);

int main()
{
    float temp ;
    char unit[5] ;
    float ans ;

    temp = input_temp() ;

    strcpy(unit, input_unit()) ;

    ans = calculate(temp , unit) ;

    printf("Converted temperature is %f ." , ans);

    return 0;
}

int input_temp()
{
    float x ;

    printf("Enter the temperature : ") ;
    scanf("%f" , &x ) ;
    return x ;
}

input_unit()
{
    char Unit[5] ;
    printf("Enter the unit (C or F) : ") ;
    scanf("%s" , Unit) ;
    return Unit ;
}

calculate(float T , char U[])
{
    float convert ;
    if (strcmp(U , 'F') == 0)
    {
        convert = (T-32)*5/9 ;
    }
    else  // if(strcmp(U , 'C') == 0)
    {
        convert = (T*9/5)+32 ;
    }
    return convert ;
}

我相信我在Calculate()函数中犯了一些错误(但我不确定)。请帮我搞清楚。以及如何确定运行时错误?

c
2个回答
0
投票
strcmp(U , 'F')

是错的。你需要

strcmp(U , "F")

strcmp采用char数组而不是chars。 'F'成为char'F'的整数值 - 例如。在ASCII中它是70.所以strcmp查找从地址70开始的字符数组。


0
投票

除了char之外,没有必要存储所需的单位。通过其他一些清理:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

float calculate(float T , char unit);
float input_temp();
char input_unit();

int main()
{
    float temp ;
    char unit;
    float ans ;

    temp = input_temp();
    unit = input_unit();
    ans = calculate(temp ,unit);

    printf("Converted temperature is %f.\n" , ans);
    return 0;
}

float input_temp()
{
    float x ;

    printf("Enter the temperature : ") ;
    scanf("%f" , &x ) ;
    return x ;
}

char input_unit()
{
    char U[5];
    printf("Enter the unit (C or F) : ") ;
    scanf("%s" , U) ;
    if (strcmp(U, "F") == 0) {
        return 'F';
    }
    return 'C' ;
}

float calculate(float T , char U)
{
    float convert ;
    if (U == 'F')
    {
        convert = (T-32)*5./9 ;
    }
    else
    {
        convert = (T*9./5)+32 ;
    }
    return convert ;
}
© www.soinside.com 2019 - 2024. All rights reserved.