如何将用户输入的char字符存储到变量/数组中?

时间:2018-10-11 21:49:23

标签: char scanf

我正在制作一个单位转换器计算器(忽略几个函数名称的取反),并且试图存储用户输入的char字符(即m,g或c) )代表要转换的单位。我的代码卡在了scanf()函数中,不确定当我将char userUnit的长度指定为2时,为什么它不会占用单个array字符的原因。保留空终止符)。有什么想法吗?

#include <stdio.h>

//Function prototypes
double fahrToCelc(double cel);
double meterToFoot(double foot);
double poundToGram(double pound);

int main(){
    double conversions;
    char userUnit[2];
    char letter[4] = "gmc";

    //User inputs
    scanf("%lf %s",&conversions, userUnit);

    if(userUnit[0] == letter[0]){        
        printf("%.6lf lb",poundToGram(conversions));

    }else if(userUnit[0] == letter[1]){
        printf("%.6lf ft",meterToFoot(conversions));

    }else if(userUnit[0] == letter[2]){        
        printf("%.6lf f",fahrToCelc(conversions));
    }

    return 0;    
}

//Function declarations
double fahrToCelc(double cel){
    double fahr = 32 +(1.8*cel);
    return printf("%lf",fahr);
}

double meterToFoot(double meter){
    double foot = meter*0.3048;    
    return printf("%lf", foot);
}

double poundToGram(double gram){
    double pound = gram/0.002205;    
    return printf("%lf",pound);
}

0 个答案:

没有答案