gpt4 book ai didi

c - 在C中将信息存储到变量中的问题

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

我编写了以下代码来介绍 C 类。但是由于某种原因我无法弄清楚为什么 scanf不会将输入存储到华氏变量中,因此不允许我正确进行计算。我将起始值从 0 更改为 212,以确保我的计算正确,但它仍然不允许我更新。

 #include <stdio.h>
int main(void){

double fahrenheit = 212.00;
double celcius = 0;

//prompt the user for the information
printf("Enter a temperature in degrees Fahrenheit >");

//store the information in the Fahrenheit var.
scanf("%f", &fahrenheit);
//calculate the change in metrics
celcius = (fahrenheit-32)*.5556 ;
printf("%f degrees Fahrenheit is equal to %f degrees celcius\n",fahrenheit,celcius);
}

最佳答案

double 参数一起使用的正确 printfscanf 格式是 %lf。不是%f,而是%lf。不要将 %fdouble 一起使用。应该是

scanf("%lf", &fahrenheit);
...
printf("%lf degrees Fahrenheit is equal to %lf degrees celcius\n",
fahrenheit, celcius);

请注意,%f 将与 printf 中的 double 一起使用(不在 scanf 中),但使用它这种方式仍然是一个坏习惯,这只会让初学者产生这样的误解:printfscanf 在这方面某种程度上“不一致”。

格式说明符和参数类型之间的匹配定义明确,并且在 printfscanf 之间保持一致:

  • %f 代表 float
  • %lf 代表 double
  • %Lf 代表 long double

关于c - 在C中将信息存储到变量中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222161/

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