【问题标题】:C Temperature Conversion Program Keeps Outputting 0 For Fahrenheit to Celsius [duplicate]C温度转换程序不断输出华氏到摄氏度的0 [重复]
【发布时间】:2014-03-04 04:30:21
【问题描述】:

当我尝试将华氏温度转换为摄氏温度时,我的 C 温度转换程序一直输出 0。从摄氏度到华氏度的转换似乎工作得很好。我对函数和部分都做了完全相同的事情,但是第二次转换我一直得到 0。有人可以帮助我或告诉我我做错了什么吗?

#include <stdio.h>

//Function Declarations

float get_Celsius (float* Celsius);       //Gets the Celsius value to be converted.
void to_Fahrenheit (float cel);           //Converts the Celsius value to Fahrenheit and prints   the new value.
float get_Fahrenheit (float* Fahrenheit); //Gets the Fahrenheit value to be converted.
void to_Celsius (float fah);              //Converts the Fahrenheit value to Celsius and prints the new value.

int main (void)
{
   //Local Declarations
   float Fahrenheit;
   float Celsius;
   float a;
   float b;

   //Statements
   printf("Please enter a temperature value in Celsius to be converted to Fahrenheit:\n");
   a = get_Celsius(&Celsius);
   to_Fahrenheit(a);
   printf("Please enter a temperature value in Fahrenheit to be converted to Celsius:\n");
   b = get_Fahrenheit(&Fahrenheit);
   to_Celsius(b);

   return 0;
} //main

float get_Celsius (float* Celsius)
{
   //Statements
   scanf("%f", &*Celsius);
   return *Celsius;
}

void to_Fahrenheit (float cel)
{
   //Local Declarations
   float fah;

   //Statements
   fah = ((cel*9)/5) + 32;
   printf("The temperature in Fahrenheit is: %f\n", fah);
   return;
}

float get_Fahrenheit (float* Fahrenheit)
{
   //Statements
   scanf("%f", &*Fahrenheit);
   return *Fahrenheit;
}

void to_Celsius (float fah)
{
   //Local Declarations
   float cel;

   //Statements
   cel = (fah-32) * (5/9);
   printf("The temperature in Celsius is: %f\n", cel);
   return;
}

【问题讨论】:

  • 哦,哇,我什至没有看到与我几乎相同的问题。对于重复我是这个网站的新手,我深表歉意。
  • 至少你下次知道。不过,作为一般规则,像这样的大多数初学者类型问题至少被问过一次(在这种情况下,是几次),在你发布之前,你应该已经看到了很多可能相关的问题。

标签: c output stdio temperature


【解决方案1】:
cel = (fah-32) * (5/9);

这里5/9是整数除法,结果是0,改成5.0/9


在几行中,您正在使用

scanf("%f", &*Celsius);

&amp;* 不是必需的,只需 scanf("%f", Celsius); 即可。

【讨论】:

  • scanf("%f", Celsius); 我想这行不通。至少你需要 &
  • 非常感谢,我知道这很愚蠢,但我无法弄清楚它是什么。也许我应该乘以 5.0/9 创建的小数。尽管如此,还是感谢您的帮助。
  • @Abhay Celsius 在该函数中有 float * 类型。不过变量命名不好,因为main 中的同名Celsius 具有float 类型。
  • @YuHao 感谢您的建议和帮助。我仍然在使用 C 中的一些与我习惯不同的语法。还有一段时间不编程。
【解决方案2】:
cel = (fah-32) * (5/9);

5/9int/int 并会在 int 中为您提供结果,因此是 0

改成

cel = (fah-32) * (5.0/9.0);

cel = (fah-32) * ((float)5/(float)9);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多