Conversion from double to integer [duplicate]

时光毁灭记忆、已成空白 提交于 2019-12-04 06:24:02

问题


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

In this case->

int x=1000;

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

int a=cuberoot;

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

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

Output:

cuberoot=10
a=9

Why here a=9 and not 10?

Any solution to this problem??

Also I don't want to round the value..if a=3.67 then it should be converted to 3 only and not 4.


回答1:


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);



回答2:


Try this and see why!

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(){
    int x = 1000;
    double cube = pow(x, 1.0/3.0);
    int a = cube;
    cout<<"cube="<< fixed << setprecision(16) << cube<<endl;
    cout<<"a="<<a<<endl;
}


来源:https://stackoverflow.com/questions/24222701/conversion-from-double-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!