2017-07-07 115 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