簡體   English   中英

四舍五入並將其重新轉換為整數

[英]Rounding off and recast it as integer

double num1=3.3;
double num2=3.8;

//print output and round off
cout<<floor(num1+0.5)<<endl;
cout<<floor(num2+0.5)<<endl;

我的任務是先將數字四舍五入,然后將其轉換為整數:四舍五入后 num1 和 num2 的輸出應分別為3.0000004.000000 我應該如何將它轉換為int以獲得上述答案34

您可以聲明一個int變量並分配floor的結果,然后輸出該int 也不再需要地板,因為分配給int是隱式的。

int i1 = num1+0.5;
cout<<i1<<endl;

請注意,在您當前的代碼中, floor()實際上沒有任何幫助,因為您正在丟棄結果。 floor沒有修改它的參數,而是返回它的結果,並且你沒有將它分配給任何東西。 例如,您可以使用
num1 = floor(num1+0.5);
然后num1將包含結果。

cout<<floor(num1+0.5)<<endl; 將打印3.0 你不需要更多的演員在這里,但如果你想這樣做,使用static_cast

double num1=3.3;
double num2=3.8;

// to round off
int num1_as_int = static_cast<int>(floor(num1+0.5));
int num2_as_int = static_cast<int>(floor(num2+0.5));

//print output
cout<<num1_as_int<<endl;
cout<<num2_as_int<<endl;

更多static_cast這里,為什么你應該使用它來代替C風格的類型轉換這里

暫無
暫無

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

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