2016-06-12 75 views
2

我做的在C#中的一些自我教育,虽然我做了更复杂的项目比这个,我想不通的问题是什么。分割两个数字

private void button4_Click(object sender, EventArgs e) 
    { 
     int headcount = 0; 
     int input = Global.inputcount; 

     for (int i = 0; i < Global.inputcount; i++) 
     { 
      if (Global.myTextFile[i] == "F") 
      { 
       headcount++; 
      } 
     } 
     float result; 
     result = headcount/input; <<< that line 
     button4.Text = result.ToString(); 
    } 

这是我的代码,它应该算多少次的myTextFile阵列中F occour,应该除以数量与输入数量。

我调试了很多次,和一切都很好,直到[是]线。尽管(人数=〜2201)和(输入=〜4321),结果为0。

我用帕斯卡,我一直在使用C#像2个月所以如果有人能帮助我,我将不胜感激工作。

F在匈牙利

+3

这是一个整数除法,使用result =(float)headcount/input;代替。 –

+0

问题是整数除法。尝试转换为'result =(float)headcount/input;' –

+0

'int/int' ='int' - 您需要将devisee('headcount')投射到'float' – Olipro

回答

3

int/int总是忽略小数部分无论哪种类型为它分配执行integer division代表“复方阿胶浆” =“头”。

/ Operator (C# Reference)

当你把两个整数,结果始终是整数。对于 例如,7/3的结果为2.要获得的商作为理性 数或分数,得到被除数或除数float类型或键入 两倍。

你可能想使用浮点除法来代替。

result = (float)headcount/input; 

result = headcount/(float)input; 

检查7.7.2 Division operator文档以及。

0

既然你期待一个INT结果和两个操作数是INT类型,你正在0作为输出。您可能需要将其转换成float操作

headcount/(input * 1.0); 
+0

似乎OP想要得到总人数和总人数之间的比例(即期望得到0到1之间的数字)。 Alaso,请注意,由于OP使用整数除法,因此将除法得到的所有十进制值 –

+0

@GianPaolo,是的。编辑答案。 – Rahul

0

你没有做除法之前投人数或输入到浮动。它目前正在做整数除法,它不包括任何余数。总人数/输入与2201/4321相同,在整数除法中等于0。通过执行result =(float)headcount /(float)输入将它们投射到浮点。