将温度从摄氏温度转换为华氏温度

标签 c if-statement scanf

我编写了一个将温度从摄氏度转换为华氏度的程序。当我输入 c 时,代码按预期工作,但当我输入 f 时,它会给我一个随机数:

#include <stdio.h>

int main (void){
    float f,c;

    printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
    if(scanf("c",&c)==c){
        printf("Grad Celisius =");
        scanf("%f",&c);
        f=(c*1.8)+32;
        printf("%.2f Grad Celisius sind %.2f Grad Fahreiheit\n",c,f);
    }
    else if(scanf("f",&f)==f){
        printf("Grad fahrenheit =");
        scanf("%f",&f);
        c=(f-32)/1.8;
        printf("%.2f Grad Fahrenheit sind %.2f Grad Fahrenheit",f,c);
    }
    return 0;
}

如何解决我的问题?

最佳答案

您没有使用scanf()正确指挥。我稍微修改了你的代码,这对我有用:

#include <stdio.h>

int main (void){
    float f,c;
    char ch;

    printf("x=Ende c=Umrechnung c->f f=Umrechnung f->c:");
    scanf(" %c", &ch);
    if(ch=='c'){
        printf("Grad Celsius =");
        scanf("%f",&c);
        f=(c*1.8)+32;
        printf("%.2f Grad Celsius sind %.2f Grad Fahrenheit\n",c,f);
    }
    else if(ch=='f'){
        printf("Grad Fahrenheit =");
        scanf("%f",&f);
        c=(f-32)/1.8;
        printf("%.2f Grad Fahrenheit sind %.2f Grad Celsius",f,c);
    }
    return 0;
}

基本上,您只读取了一个字符 (ch) 一次,然后将其与程序提供的选项进行比较。请注意 scanf() 行中 "%c" 中的空格字符。可能需要它才能使代码正常工作,如here所述。 .

我猜您还想在代码周围放置一个循环,这样就可以要求用户输入 x 来结束程序。目前,如果您不输入 cf,程序就会终止。程序也会在完成一次计算后终止。

顺便说一下,我还在您的最后一个 printf() 中将一个 摄氏 更改为 华氏。我认为你混淆了那里的词。我还将 Celisius 更改为 Celsius

关于将温度从摄氏温度转换为华氏温度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583413/

相关文章:

bash - 将文件中的键/值参数读取到 shell 脚本中

c - 设计一个函数,使其在 C 中没有全局变量

c - 有没有计算进程运行时间的C函数?

r - 如何使用 R 中的 if 语句将唯一函数应用于数据集的多行?

javascript - 在 if 语句中排除所有其他事件 ID

c - “', '\n”、scanf() 和输出屏幕

c - 使用 scanf 分配指针的 char 数组

c - 用于输入的 fgets()/sscanf 在功能上运行良好。当 fnct 离开并返回时,stdin 中是否有额外的输入/行?

c - C语言如何查找句子中的字符

C 程序拒绝管道?