簡體   English   中英

C++中int類型到double類型以及不同類型的算術運算結果如何正確存儲?

[英]How to correctly store the result of arithmetic operations on int type to double type and different types in C++?

我有兩次存儲在struct中的int類型中,想要計算編號。 兩次之間經過的小時數。 如何正確地將結果存儲在double變量中。 我似乎弄錯了區別。 另外,如何將結果存儲到小數點后兩位。 這是我的代碼:

struct time
{
int hour=0,min=0;
char am_pm='a';
};

int main()
{
time t1,t2; 
// GET THE TIME INPUT FROM THE USER HERE
//assuming always t2's hour and min are always numerically greater than t1's hour and min and always `am`

double hour_diff=0.00,min_diff=0.00;
double time_elapsed=0.00;
cout<<"The time elapsed between your entered times is : ";

hour_diff=t2.hour-t1.hour; counting hour difference
min_diff=(t2.min+t1.min)/60; //counting total minutes and converting them into hours

time_elapsed=hour_diff+min_diff;
cout<<time_elapsed;

如果我給出這些輸入,當我應該得到 7.25 時,我會得到錯誤的結果 7:

INPUT
t1.hour = 5
t1.min = 30
t1.am_pm = a;

t2.hour = 11
t2.min = 45
t2.am_pm = a;

time elapsed = 7 // this is wrong, I should be getting 7.25

錯誤是因為此表達式(t2.min+t1.min)/60將返回int

那是因為(t2.min+t1.min)int類型,而60int類型。 因此\將是一個 integer 除法運算。

要解決它,您可以使用static_cast<double>(t2.min+t1.min)(t2.min+t1.min)轉換為double 查看有關static_cast的更多信息。

或者您可以通過編寫60.0簡單地將60定義為雙精度數。

由於您正在執行 integer 操作 '(t2.min + t1.min)/60',即使您將它們存儲在 double 類型的變量中,也會簡化為 integer 類型。 通過將 60 更改為“60.0”使 60 成為雙精度值,或者在操作之前使用“static_cast”包含整個結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM