[英]Fahrenheit to Celsius wrong result
我是軟件開發的學生,我需要從華氏轉換為攝氏,但是我的代碼計算錯了。 這是我的代碼:
int main() {
// configure the out put to display money
cout.setf(ios::fixed); //no scientific notation
cout.setf(ios::showpoint); //show decimal point
cout.precision(0); //two decimal for cents
int fahrenheit = 0 ;
int celsius = 5/9*(fahrenheit-32);
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit ;
cout << "Celsius: " << celsius << endl;
return 0;
}
您的公式使用的是int:5/9,這意味着您失去了一些精度,請將5更改為5.0,或者如果您想將攝氏度更改為浮動
您的代碼中有四個錯誤。
1)要點是要意識到計算機可以按照您要求的順序進行操作。 顯然,正確的順序是:a)要求用戶輸入溫度b)將其轉換為攝氏度。 但是您的代碼卻相反。 這是您的代碼,帶有我的一些注釋
// convert fahrenheit to celcius
int celsius = 5/9*(fahrenheit-32);
// ask user to enter fahrenheit temperature
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit ;
希望現在很明顯,你走錯了路
2)第二個錯誤是您為變量選擇了錯誤的類型 。 溫度不是整數(例如,溫度為80.5度沒錯)。 因此,您應該為變量選擇浮點類型 , float
是一種可能。
3)第三個錯誤是相當技術性的,但很重要。 在您的方程中,您寫了5
5/9
和9
都是整數,因此計算機將執行整數除法 ,這意味着無論除法的數學結果是什么,計算機都將舍棄結果的小數部分,從而留下一個整數。 因此,數學上5/9
為0.555555...
, 0.555555...
小數部分將留下0
,因此您的方程式與0*(fahrenheit-32)
,顯然不會給出正確的結果。 使用5.0/9.0
而不是5/9
可以得到浮點除法 。
4)最終錯誤是微不足道的
cout.precision(0); //two decimal for cents
如果要小數點后兩位
cout.precision(2);
最后,這不是錯誤,但是有關金錢的評論在有關溫度的程序中不合適。
這是修正了這些錯誤的代碼版本
int main() {
cout.setf(ios::fixed); //no scientific notation
cout.setf(ios::showpoint); //show decimal point
cout.precision(2); //two decimal places
float fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
float celsius = 5.0/9.0*(fahrenheit-32.0);
cout << "Celsius: " << celsius << endl;
return 0;
}
我敢肯定您對一個簡短的程序會出現這么多錯誤感到驚訝。 它只是強調在編寫代碼時必須小心且精確。
如果必須使用int,則應在最后一步執行除法,以減少int類型的精度損失。 但是請記住,這可能會導致int溢出(對於溫度來說應該不是問題...)
#include <iostream>
using namespace std;
int main() {
// configure the out put to display money
cout.setf(ios::fixed); //no scientific notation
cout.setf(ios::showpoint); //show decimal point
cout.precision(0); //two decimal for cents
int fahrenheit = 0 ;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit ;
int celsius = 5*(fahrenheit-32)/9;
cout << "Celsius: " << celsius << endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.