【问题标题】:Converting temperatures from Celsius to Fahrenheit将温度从摄氏度转换为华氏度
【发布时间】:2016-02-08 13:56:54
【问题描述】:

我编写了一个将温度从摄氏温度转换为华氏温度的程序。当我输入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;
}

如何解决我的问题?

【问题讨论】:

  • “这是错误的”不是错误描述。您预计会发生什么,但会发生什么?
  • 当我执行程序并输入 f 将温度从华氏温度转换为摄氏温度时,它给了我一个随机数
  • if(scanf("c",&c)==c) 你为什么写这个?
  • 创建条件(如果我输入“c”,将执行以下语法)
  • 好哥们,不幸的是 scanf 不能那样工作......

标签: c if-statement scanf


【解决方案1】:

您没有正确使用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() 里把一个Celsius 改成了Fahrenheit。我想你把那里的词弄糊涂了。我还将Celisius 更改为Celsius

【讨论】:

  • 很高兴能帮上忙!如果您觉得对您有用,请随时 accept my answer :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-23
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多