[英]data type cast int to double in cpp
為什么它打印為cout<<(4*(double)(r*r))<<endl;
作為整數,因為我的類型轉換有問題。 我必須將輸入 r 作為 int input->1 output->4
為什么cout<<setprecision(2)<<ab2<<endl;
四舍五入答案至少它應該給出正確答案直到兩位數,因為我已經設置了設置精度 2 輸入-> 1 輸出-> 3.8
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
long long int r;
cin>>r;
double ab2 = 4*(double)(r*r) - double(0.25);
cout<<4*(double)(r*r)<<endl;
cout<<setprecision(2)<<ab2<<endl;
cout<<ab2+0.25<<endl;
}
}
我猜你會看到更像你期望的代碼
int main() {
cout << fixed << setprecision(2); // fixed notation and two decimal places
int t;
cin >> t;
while (t--) {
long long int r;
cin >> r;
double ab2 = 4 * (double)(r*r) - double(0.25);
cout << 4 * (double)(r*r) << endl;
cout << ab2 << endl;
cout << ab2 + 0.25 << endl;
}
}
輸入
1 1
輸出
4.00
3.75
4.00
為什么它打印為
cout<<(4*(double)(r*r))<<endl;
作為整數
它是一個雙重的,所以它把它打印成一個雙重的。 然而,它是代表整數的雙精度數。
以及為什么
cout<<setprecision(2)<<ab2<<endl;
四舍五入的答案
因為您使用的精度小於該值的有效數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.