数据类型在 CPP 中将 int 转换为双倍

data type cast int to double in cpp

本文关键字:转换 int CPP 中将 数据类型      更新时间:2023-10-16

为什么它打印的整数cout<<(4*(double)(r*r))<<endl;就像我的类型转换有问题一样。我必须将输入 r 作为整数输入>1 输出>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;四舍五入答案

因为您使用的精度小于具有有效数字的值。