Conversion from double to integer [duplicate]

北慕城南 提交于 2019-12-02 07:45:26

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

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