C++ 简单计算输出 0.0000000000000000 而不是 0.003333

标签 c++ glm-math

dx 和 dy 的计算返回 0,我看不出问题所在。控制台似乎显示正在使用所有正确的值。

void drawBackground()
{
    double r, g, b, dx, dy, Wx, Wy, Wz; 
    Ray ray;
    cout << "xmax: " << sceneDescription::imagePlaneXmax << " xmin: " << sceneDescription::imagePlaneXmin << endl;
    cout << "ymax: " << sceneDescription::imagePlaneYmax << " ymin: " << sceneDescription::imagePlaneYmin << endl;
    cout << "Iw: " << sceneDescription::Iw << " Ih: " << sceneDescription::Ih << endl;
    cout << " " << endl;

    dx = (sceneDescription::imagePlaneXmax - (sceneDescription::imagePlaneXmin))/sceneDescription::Iw;
    dy = (sceneDescription::imagePlaneYmax - (sceneDescription::imagePlaneYmin))/sceneDescription::Ih;
    std::cout << "dx: "<< boost::format("%1$.16f") % dx << " dy: "<< boost::format("%1$.16f") % dy << endl;

}

场景描述.h

#include <glm/glm.hpp>

using namespace glm;

class sceneDescription{

public:
    static const int imagePlaneXmin = -1;
    static const int imagePlaneXmax = 1;
    static const int imagePlaneYmin = -1;
    static const int imagePlaneYmax = 1;
    static const int Iw = 600;
    static const int Ih = 800;
};

控制台输出:

xmax: 1 xmin: -1

ymax: 1 ymin: -1

Iw: 600 Ih: 800


dx: 0.0000000000000000 dy: 0.0000000000000000

最佳答案

问题在于语句:

dx = (sceneDescription::imagePlaneXmax -
(sceneDescription::imagePlaneXmin))/sceneDescription::Iw;

将给出以下结果:

(1-(-1))/600 = 2/600 = 0.00 (since this is integer division). 

您可能希望将数字转换为double

像这样的东西会起作用:

dx = (double)(sceneDescription::imagePlaneXmax -
(sceneDescription::imagePlaneXmin)) / sceneDescription::Iw;

由于转换运算符的优先级高于除法,分子将由 (double) 转换,分母将隐式转换为 double 结果。

希望对您有所帮助!

关于C++ 简单计算输出 0.0000000000000000 而不是 0.003333,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29615059/

相关文章:

c# - 为什么这个表达式在 C# 和 C++ 中产生不同的结果?

c++ - 窗口坐标到摄像机角度?

c++ - SHFileOperation 不会 move 文件夹的所有内容

c++ - Opencv - 释放内存将 cv::Mat refcount 更改为零

C++ stoi 超出范围问题

c++ - CRLF 行尾和 ostringstream

c++ - 绕错误的轴旋转

c++ - 如何用glm旋转3D相机

c++ - 如何从 View 投影矩阵检索相机原点/位置? (OpenGL)

c++ - 检查是否设置了 glm::vec3