将两个数相除 [英] Dividing two numbers

查看:46
本文介绍了将两个数相除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C#进行一些自我教育,尽管我做的项目比这还要复杂,但我无法弄清楚问题出在哪里.

  private void button4_Click(对象发送者,EventArgs e){int员工人数= 0;int输入= Global.inputcount;对于(int i = 0; i< Global.inputcount; i ++){如果(Global.myTextFile [i] =="F"){人数++;}}浮动结果;结果=人数/投入;<<<那条线button4.Text = result.ToString();} 

这是我的代码,它应该计算 myTextFile 数组中 F 发生了多少次,并且应该将该数字除以输入数量./p>

我调试了很多次,一切都很好,直到该行为止.尽管存在(人数=〜2201)和(输入=〜4321)的事实,结果仍为0.

我曾经使用过Pascal,我已经使用C#大约2个月了,所以如果有人可以帮助我,我将不胜感激.

F 在匈牙利语中代表"Fej" ="Head"

解决方案

int/int 执行 /运算符(C#参考)

当您将两个整数相除时,结果始终是整数.为了例如,7/3的结果为2.数字或分数,给出除数或除数类型float或type

您可能想改用浮点除法.

  result =(浮动)人数/输入; 

  result =人数/(浮动)输入; 

检查 7.7.2除法运算符文档.

I'm doing some self-education in C#, and although I did more complex projects than this, I can't figure out what the problem is.

    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();
    }

This is my code, its supposed to count how many times does F occour in the myTextFile array, and it should divide that number with the number of inputs.

I debugged it many times, and everything is fine until [that] line. Result is 0 despite the fact that (headcount = ~2201) and (input = ~4321).

I used to work with pascal, I've been using C# for like 2 months so if anyone can help me out i would be grateful.

F stands for "Fej" = "Head" in Hungarian

解决方案

int / int performs integer division which always disregards fractional part no matter which type you assign it.

From / Operator (C# Reference)

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double.

You might wanna use floating-point division instead.

result = (float)headcount / input;

or

result = headcount / (float)input;

Check 7.7.2 Division operator documentation as well.

这篇关于将两个数相除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆