2017-07-07 197 views
-3

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

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.

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'的无效操作数和'双'到二进制'运算符%)。你能告诉我如何解决这个问题?

+0

INT int_value =的static_cast (STD: :轮(float_value)); [已经在这里回答](https://stackoverflow.com/a/16570752/4953089) – VKadiyski

回答

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来代替。

+0

感谢您的意见,我使用的格式根据您的意见,但现在仍然编程输出显示错误和输出显示/ /无效类型'int'和'double'的操作数转换为二进制'operator%'。 。你能否给我另一个想法? – mizan

+0

嗨编程正在运行,但输出是错误的。我发现输出保持counter2 [cell_particle]是错误的值,但我不明白为什么? – mizan

0

得到5出5.4 6出的5.6,你可以轻松地轮数ceil(5.4)如果你想获得更高的比例或floor(5.6)如果要降低那些

+0

感谢您的意见,我根据您的意见使用格式,但现在编程输出显示错误和输出显示//类型'int'和'double'的无效操作数到二进制'操作符%'。 。你能否给我另一个想法? – mizan