Search code examples
c#percentage

How to get percentage on c# in school fail rate


Hi there. I just wanted to get the fail rate in score of the exam and I tell you here what each variable name means:

*

tedad= number of student//- tedad fale = number of students who fails//- darsad gaboli= percentage of students who pass the exam//- tedad nomarat ra vared konid = enter the amount of numbers you wanna enter//- Tedad ra dorost vared konid= enter the numbers in the correct format (be aware in my country scores are from 20 means 0-20 and if you get under 10 you will fale)// ignore comments in code :)//- Majmo nomre: sum of scores//-

* the main problem is float a contains 0 when I divide tedadfail with tedad but when I do the opposite it shows the correct number how can I fix this?

int tedad, tedadfaile = 0;
    float avg, sum = 0;
    //gereftan tedad
    Console.WriteLine("Tedad ra vared konid: ");
    while (1 > 0)
    {
        tedad = Convert.ToInt32(Console.ReadLine());
        if (tedad<=0)
        {
            Console.WriteLine("Tedad ra dorost vared konid.");
            continue;
        }
        if(tedad>0)
        {
            break;
        }
    }

    float[] scorre = new float[tedad];
    
    //gereftan nomre

    Console.WriteLine("Nomarat ra vared konid: ");
    
    for(int i=0; i<tedad;i++)
    {
        scorre[i] = Convert.ToInt32(Console.ReadLine());

        if (scorre[i] < 0 || scorre[i] > 20)
        {
            Console.WriteLine("Lotfan nomre dorost ra vared konid.");
            continue;
        }

        if(scorre[i] < 10)
        {

            tedadfaile=tedadfaile+1;
            
        }
    }
    
    //jam kardan nomre

    for(int i=0; i<tedad;i++)
    {
        sum = sum + scorre[i];
    }

    //miangin

    avg = sum / tedad;

    //darsad gaboli

    float a =(tedadfaile)/( tedad);
    float b = 100 - a;
    
    Console.WriteLine(" Nomarat dar class " + tedad +" nafari:\nMajmo nomre:"+sum+"\nMIangin:"+avg+"\nMiangin gaboli: "+b+" darsad");

Solution

  • You're not the first to make this mistake:

    float a =(tedadfaile)/( tedad);
    

    tedadfaile and tedad are both integer numbers.
    So, what you are doing, is dividing two integer numbers, which automatically means that you are using integer division, and only afterwards are you turning that result into a floating point value.

    You can do the following in order to force floating point arithmetic:

    float a =((float)tedadfaile)/( tedad);
    

    Which means: turn at least one of the numbers into a floating point number, in order to force floating point arithmetic.