我正在使用 Eigen 库编写 C++ 程序,当我执行我的代码时,我得到了我的变量 P
`-4 -3 -2 -1 0 1 2 3 4 5`
但应该是-4.5 -3.5-2.5-1.5-0.5 1.5 2.5 3.5 4.5
数字四舍五入到最接近的整数,接近无穷大。请帮我找到解决问题的方法。
#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<eigen3/Eigen/Dense>
#include<eigen3/Eigen/Core>
using namespace Eigen;
using namespace std;
using Eigen::MatrixXd;
using Eigen::MatrixXf;
MatrixXf create_linear_array(int &N1 , double &dx)
{
int i;MatrixXf num(10,1);
for(i=0;i<10;i++)
num(i,0)=(float)(((i+1)-(N1+1)/2));
return num;
}
int main()
{
//---------------------INITIALISATION & DECLARATION------------------------------
double dx=0.030;
int N1=10;
MatrixXf P;
P=create_linear_array(N1,dx);
cout<<P<<endl;
return 0;
}
最佳答案
你正在做整数除法,整数除法的结果总是一个整数。之后才将结果转换为 float ,但为时已晚。解决此问题的最简单方法是使用浮点文字 2.0
而不是 2
。这是可行的,因为 2.0
是一个 double ,当您将一个整数除以一个 double 时,该整数会先转换为 double 。
num(i,0)=(float)(((i+1)-(N1+1)/2.0));
关于c++ - 在函数定义中使用 Eigen 库时,小数点未按预期存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092982/