gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:24:25 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com