[英]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.000000
和4.000000
。 我應該如何將它轉換為int
以獲得上述答案3
和4
?
您可以聲明一個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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.