数据类型在 CPP 中将 int 转换为双倍
data type cast int to double in cpp
为什么它打印的整数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;
四舍五入答案
因为您使用的精度小于具有有效数字的值。
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用