Click here to Skip to main content
15,041,391 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Everyone!

I am Creating Marks Percentage Program In C#,but i still Got Percentage(0,0,0,0,0,0). Please Tell Me Error In It.

C#
static void Main(string[] args)
{
    int[] number = new int[6];
    float[] percentage = new float[6];
    int x;
    Console.WriteLine("Enter Number.");
    for (x = 0; x < 6; x++)
    {
        Console.Write("Enter Subject {0} Marks.", x + 1);
        number[x] = Convert.ToInt32(Console.ReadLine());
    }
    Console.WriteLine("Percentaeg of Marks Is.");
    for (x = 0; x < 6; x++)
    {
        percentage[x] =(float)((number[x] / 100) * 100);
      //  Console.WriteLine(Math.Round(percentage[x]));
    }
    foreach (int per in percentage)
    {
        Console.WriteLine(per);
    }
    Console.ReadLine();


}
Posted

Integer arithmetic!
Your user enters 25 say.
C#
25 / 100 = 0
No really - this is integer arithmetic, so it can't work with fractions. Try changing to float earlier:
C#
percentage[x] =(((float)number[x] / 100) * 100);

Or multiply first:
C#
percentage[x] =(float)((number[x] * 100) / 100);

Or throw away the mutiplication and division:
C#
percentage[x] =(float)number[x];

Or better, use floats throughout:
C#
float[] number = new float[6];
float[] percentage = new float[6];
int x;
Console.WriteLine("Enter Number.");
for (x = 0; x < 6; x++)
{
    Console.Write("Enter Subject {0} Marks.", x + 1);
    number[x] = Convert.ToFloat(Console.ReadLine());
}
Console.WriteLine("Percentaeg of Marks Is.");
for (x = 0; x < 6; x++)
{
    percentage[x] =(number[x] / 100) * 100;
But then, the multiplication and division are redundant!
   
Comments
   
5ed.
—SA
You were tricked by .Net's number handling. When you divide an int by another int, the result is an int - it has already lost all its decimal places. When you now cast it to a float, those decimal places cannot appear again.

Hence you must trick .Net to do the conversions you need:

When you divide an int by a float, .Net converts the int to a floating point number, and the result is a floating point number. Well, double might be the type of the result, I am not fully sure about its preferences. Anyway, double is the "normally used" type of floating point numbers.

Also, dividing a number by 100 and multiplicating it by 100 doesn't change it - you got confused here. Sum up all the numbers.

double[] percentage = new double[6];
percentage[x] = 100.0 * number[x] / sum;
100.0 is interpreted as a double, and that will do the trick.
   
In addition of OriginalGriff's answer, i'd suggest to read this: float (C# Reference)[^]. Follow the links provided on the bottom of relevant page.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900