【问题标题】:Conversion from double to integer [duplicate]从双精度转换为整数 [重复]
【发布时间】:2014-06-14 17:57:32
【问题描述】:

我遇到了双数没有正确转换为整数的问题。

在这种情况下->

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?

有解决这个问题的办法吗??

另外我不想四舍五入值..如果 a=3.67 那么它应该只转换为 3 而不是 4.

【问题讨论】:

  • 您可以在数字上加上一个小的正数,然后计算根。喜欢x=1000+0.05。这将给a=10
  • 不是cube - 那是x^3

标签: c++ integer decimal pow


【解决方案1】:

因为cuberoot 非常接近 10 但不完全是 10。std::cout 将数字截断并四舍五入为 10,但双精度到整数的转换会去除小数,这就是为什么 a = 9。要解决这个问题,可以使用std::round()

int a=round(cuberoot);

【讨论】:

  • 那么有什么解决方案可以让 a=10 在这里?
  • 使用 round() 函数。
  • 其实问题是我不想精确地舍入。
  • 我希望如果 a=3.99 那么它应该只转换为 3....任何解决方案?
  • 现在 cube = 9.99... 并将其转换为 a=9
【解决方案2】:

试试这个,看看为什么!

#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;
}

【讨论】:

    猜你喜欢
    • 2014-11-10
    • 2014-04-18
    • 2018-07-24
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2016-03-13
    • 1970-01-01
    相关资源
    最近更新 更多