2011-02-03 27 views
7

我正在寫一個程序的一類,我在和需要一些幫助程序在華氏C.轉換爲攝氏我的代碼看起來像這樣C程序把華氏轉換爲攝氏

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

int fahrenheit; 
double celsius; 

printf("Enter the temperature in degrees fahrenheit:\n\n\n\n"); 
scanf("%d", &fahrenheit); 
celsius = (5/9) * (fahrenheit-32); 
printf ("The converted temperature is %lf\n", celsius); 

return 0; 

} 

每次我執行它的結果是0.000000。我知道我錯過了一些東西,但無法弄清楚什麼。

+6

您與整數工作,你需要用浮點或雙精度工作。 – Joe 2011-02-03 19:04:34

+2

注意,編譯器通常認爲5.0是雙精度。你必須說5.0f做浮動價值計算。看起來與手機 – 2012-03-29 22:51:17

回答

21

5/9會導致整數除法,這將= 0

嘗試5.0/9.0代替。

+3

更相關,從技術上講,5/9.0就足夠了 – 2011-02-03 19:06:19

+0

它的工作!非常感謝:) – James 2011-02-03 19:07:50

0

您需要使用浮點運算才能以任何準確度執行這些類型的公式。如果需要,您總是可以將最終結果轉換回整數。

0

5/9.0而不是5/9 - 這迫使雙師

2

嘗試celsius = ((double)5/9) * (fahrenheit-32);或者你可以使用5.0。

事實是「/」看操作數類型。在int的情況下,結果也是一個int,所以你有0。當5被視爲double時,那麼除法將被正確執行。

8

您的問題就在這裏:

celsius = (5/9) * (fahrenheit-32); 

5/9總會給你0。改用(5.0/9.0)。

0

當處理浮動,它需要5.0f/9.0f。

當處理雙打時,它需要5.0/9.0。

當處理整數時,餘數/分數總是被截斷。 5和9之間的結果在0和1之間,所以它每次都被截斷爲0。這會使對方乘以零,並且每次都會完全廢除您的答案。

-4
using System; 


public class Calculate 
{ 

public static void Main(string[] args) 
{ 
    //define variables 
    int Celsius; 
    int fahrenheit; 
    string input; 

    //prompt for input 
    //read in the input and convert 
    Console.WriteLine("Enter Celsius temperature"); 
    input = Console.ReadLine(); 
    Celsius = Convert.ToInt32(input); 

    //calculate the result 
    fahrenheit = ((Celsius * 9)/5) + 32; 

    //print to screen the result 
    Console.WriteLine("32 degrees Celsius is {0}", "equivilant to 89.60 degrees fahrenheit"); 

    Console.ReadLine(); 
}