Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Math Issue in C#

I have this program that takes 3 scores out of a possible 200 each then is supposed to get the average and display the percentage. but when i input numbers i get 00.0 as an answer. What could i be doing wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int Score1;
            int Score2;
            int Score3;

            Console.Write("Enter your score (out of 200 possible) on the first test: ");

            Score1 = int.Parse(Console.ReadLine());
            Console.Write("Enter your score (out of 200 possible) on the second test: ");

            Score2 = int.Parse(Console.ReadLine());
            Console.Write("Enter your score (out of 200 possible on the third test: ");

            Score3 = int.Parse(Console.ReadLine());
            Console.WriteLine("\n");

            float percent = (( Score1+ Score2+ Score3) / 600);

            Console.WriteLine("Your percentage to date is: {0:00.0}", percent);
            Console.ReadLine();
        }
    }
}
like image 795
Fred Avatar asked Sep 13 '10 08:09

Fred


3 Answers

You're dividing an integer by an integer - that always uses integer arithmetic, even when you're assigning the result to a float. The simplest way of fixing that is to make one of the operands a float, e.g.

float percent = (Score1 + Score2 + Score3) / 600f;

Note that this won't actually give you a percentage though - it'll give you a number between 0 and 1 (assuming the inputs are between 0 and 200).

To get an actual percentage, you need to multiply by 100 - which is equivalent to only dividing by 6:

float percent = (Score1 + Score2 + Score3) / 6f;
like image 181
Jon Skeet Avatar answered Sep 24 '22 17:09

Jon Skeet


You are not calculating a percentage. Imagine the user enters maximum score: 200 + 200 + 200 = 600, that gets divided by 600 = 1. If any one of the scores get entered below 200, the total will be less than 1 and get rounded down to 0. You should store them as floats (to make sure you lose no information to rounding) and multiply by 100.

like image 23
MrFox Avatar answered Sep 25 '22 17:09

MrFox


It's a datatype problem, I think. You should typecast one of the scores to float, since your variable percent is float, and all the scores is int.

like image 26
arscariosus Avatar answered Sep 24 '22 17:09

arscariosus