2013-12-07 108 views
1

我有一個函數:爲什麼這個功能不輸出小數

void LocalMax(vector<Station> Entry , int Size) 
{ 
    int Highest1 = 0, Highest2 = 0, Highest3 = 0, Temp = 0, Highest = 0; 
    double TempDouble; 
    for (int i = 0; i < Size - 1; i++) 
    { 
     Temp = Entry[i].MaxTemp; 
     if (Temp > Highest) {Highest = 0; Highest = Temp;} 
     if (Entry[i].StationID != Entry[(i + 1)].StationID) 
      { 
       if (Entry[i].StationID == "GHCND:USC00083909") {Highest1 = Highest; Highest = 0;} 
       if (Entry[i].StationID == "GHCND:USW00012888") {Highest2 = Highest; Highest = 0;} 
       if (Entry[i].StationID == "GHCND:USR0000FCHE") {Highest3 = Highest;} 
      } else if (Temp > Highest) {Highest = Temp; Temp = 0;} 
     if (i == Size - 2) {Highest3 = Highest;} 
    } 
    TempDouble = Highest1/10; 
    cout << "The highest temp recorded for Station1 was: " << Highest1 << " tenths of a degree Celsius \nor: " << TempDouble << " degrees Celsius." << endl; 
    TempDouble = Highest2/10; 
    cout << "The highest temp recorded for Station2 was: " << Highest2 << " tenths of a degree Celsius \nor: " << TempDouble << " degrees Celsius." << endl; 
    TempDouble = Highest3/10; 
    cout << "The highest temp recorded for Station3 was: " << Highest3 << " tenths of a degree Celsius \nor: " << TempDouble << " degrees Celsius." << endl; 
} 

,讓我:

 
The highest temp recorded for Station1 was: 339 tenths of a degree Celsius 
or: 33 degrees Celsius. 
The highest temp recorded for Station2 was: 350 tenths of a degree Celsius 
or: 35 degrees Celsius. 
The highest temp recorded for Station3 was: 344 tenths of a degree Celsius 
or: 34 degrees Celsius. 

爲何不顯示任何TempDouble小數?任何澄清將是偉大的!提前致謝。

回答

5

您的代碼執行整數除法。這是因爲兩個操作數都是整數。

TempDouble = Highest1/10; 

整數除法得出整數結果。是的,您確實將該整數賦值爲浮點值,但已爲時過晚。你已經失去了部門的一小部分。

您需要至少使其中一個操作數成爲實際值才能真正劃分。

例如:

TempDouble = Highest1/10.0; 
+0

非常感謝您的快速回復。我很感激! – user3073174

2

該行執行整數界線,因爲左和/右操作數int S:

TempDouble = Highest1/10; 

要獲得double,保證了一操作數是double。最簡單的方法是:

TempDouble = Highest1/10.0; 
2

整數算術運算的結果是一個整數。如果你想得到一個浮點數結果,你需要在表達式中包含一個浮點數,例如:

TempDouble = Highest1/10.0; 
+0

感謝您的回覆! – user3073174