c++浮点问题
我是 C++ 和一般编程的新手。我正在尝试一些小程序只是为了亲自动手。下面是我创建的用于计算圆锥体体积的程序。
问题:无论我做什么,输出始终是一个整数。我想把它精确到小数点后两位。我尝试将变量更改为 double 和 long double 以获得更高的精度,但没有任何效果。
我该如何解决这个问题?为什么会发生这种情况? (如果可能的话详细一点) 我什至问过几位UNi的初级讲师,到目前为止没有人给我正确的答案。
int main (){
float radius,length,volume ;
const float PI =22/7.0f;
cin >> radius >> length;
volume =1/3.0f *radius*radius*length;
cout << "Volume is " << volume <<endl;
return 0;
}
我在 Fedora 上使用 g++
编辑:我早些时候尝试过使用 50 60/70 50 /120 40 等输入,它给出整数。较小的输入(如 3 4)给出小数。
编辑:set precision() 有效。感谢大家发送此信息
I'm new to C++ and programming in general . I'm trying out small programs just to get my hand dirty . Below is a program I created for calculating the volume of a cone.
Problem : No matter what I do the output is always an integer . I want to get it to two decimal points accuracy . I've tried changing the variables to double and long double to get higher precision and nothing works.
How can I fix this? And why is this happening ? (In detail if possible) I've even asked few junior lecturers at UNi so far no one gave me a proper answer.
int main (){
float radius,length,volume ;
const float PI =22/7.0f;
cin >> radius >> length;
volume =1/3.0f *radius*radius*length;
cout << "Volume is " << volume <<endl;
return 0;
}
I'm using g++ on Fedora
EDIT : I Tried this earlyer with inputs like 50 60/70 50 /120 40 which gives integers. Smaller inputs like 3 4 gives decimals.
EDIT : setprecision() works. thanks for everyone for sent this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能需要使用输出操纵器:
http://www.cplusplus.com/reference/ iostream/manipulators/set precision/
使其看起来像:
You may need to use output manipulators:
http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
so that it looks like:
我没有发现您的代码有任何问题,并且我无法重现您报告的行为。
话虽如此,如果我是你,我会尝试
set precision()< /代码>
:
I don't see anything wrong with your code, and I cannot reproduce the behaviour you're reporting.
Having said that, if I were you I'd experiment with
setprecision()
:上面发布的程序(添加缺少的
#include
和using namespace std;
)为我生成了小数点后的几个数字。如果您希望它在小数点后精确生成两位小数,则需要使用类似以下内容:在输出之前的某个位置(后一个操纵器在
中声明)。默认精度是使用 6 位数字并决定如何最好地分配它们(这可能意味着如果值变得太大或太小,输出将采用科学记数法)。顺便说一句,不要使用 std::endl 除非您确实想刷新输出流。我发现了几个案例,其中 std::endl 的不当使用变成了主要的性能问题。
The program as posted above (adding the missing
#include <iostream>
andusing namespace std;
) produces several digits after the decimal point for me. If you want it to produce exactly two decimal after the decimal point you need to use something like this:somewhere prior to your output (the latter manipulator is declared in
<iomanip>
). The default precision is to use 6 digits and decide how to best distribute them (this may mean the output goes to scientific notation if the values become too big or too small).BTW, don't use
std::endl
unless you really want to flush your output stream. I found several cases where the inappropriate use ofstd::endl
turned into a major performance issue.