如何从浮点数模数中获取提取整数?

时间:2017-07-07 06:45:01

标签: c++



const int npart = 500;
double  x[npart], y[npart], z[npart];
bedheight of yaxis, ly=20, x_axis lx=20 and z_axis lz=20
int cell_height=4;
 
const int number_cell = 5;// (ly/cell_height);
int counter2[number_cell];
int cell_particle;

for (h=0;h<number_cell;h++)
      {
    counter2[h]=0;
      }
          for (i = 0; i < npart; i++)
          {
                 //cell_particle=int(y[i]) % cell_height;
                 cell_particle= int(fmod (y[i],cell_height));
              counter2[cell_particle]=counter2[cell_particle]+1;
           }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<"     position="<<(y[j])<<endl;
 sol_fract=counter2[i]*(Volume of particle/(lx*lz*cell_height));

Could you please tell why the counter2[cell_particle] and sol_fract is contain wrong value? I am waiting for your suggestion.
&#13;
&#13;
&#13;

int number_cell=20;
int  counter2[20];
double y[500];
int cell_height=4;

for (h=0;h<number_cell;h++)

      {
        counter2[h]=0;
      }
        for (i = 0; i < npart; i++)

        {
         cell_particle=int((y[i]) % cell_height);
         counter2[cell_particle]=counter2[cell_particle]+1;
            }
cout<<"particle counter="<<counter2[j]<<"      cell number="<<cell_particle<<endl;

output: error: invalid operands of types ‘double’ and ‘double’ to binary ‘operator%

如何从模数的双倍值得到整数?注意y [i]的值= 4.5,8.9,6等我需要整数值来放置counter2数组,但问题是转换(错误消息是错误:类型'double'和'的无效操作数double'到binary'运算符%)。你能告诉我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

使用int((y[i]) % cell_height),您尝试将整个表达式(y[i]) % cell_height转换为int

您可能想要int(y[i]) % cell_height之类的东西,在模数之前将y[i]转换为int 。或者我更喜欢static_cast<int>(y[i]) % cell_height

或者,如果您想使用浮点模来代替std::fmod

答案 1 :(得分:0)

要获得5.6中的5个 6中的5个,如果您想获得更高的比例,可以轻松地舍入数字ceil(5.4)floor(5.6)如果要降低数字fetch那些