从double转换为整数 [英] Conversion from double to integer

查看:223
本文介绍了从double转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到问题,其中双号未正确转换为整数。

I am stuck in problem where the double number is not getting properly converted to integer.

在这种情况下 - >

int x=1000;

double cuberoot=pow(x,(1/(double)3));

int a=cuberoot;

cout<<"cuberoot="<<cuberoot<<endl;

cout<<"a="<<a<<endl;

输出:

cuberoot=10
a=9

为什么这里a = 9而不是10?

Why here a=9 and not 10?

这个问题的任何解决方案??

Any solution to this problem??

我也不想圆值...如果a = 3.67那么它应该只转换为3
而不是4。

推荐答案

因为 cuberoot 非常接近10但不是10。 std :: cout 截断并舍入number为10,但是double到整数转换将删除小数,这就是 a = 9 的原因。要解决此问题,您可以使用 std :: round()

Because the cuberoot is very close to 10 but not quite 10. std::cout truncates and rounds the number to 10, but a double to integer conversion will strip the decimal which is why a = 9. To solve this problem, you can use std::round():

int a=round(cuberoot);

这篇关于从double转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆