views:

278

answers:

4
+16  A: 

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;
Jon Skeet
Woot? How were you able to type that in less than 33 seconds? :-P
Patrick
@Patrick: First line from here: http://meta.stackoverflow.com/questions/9134/jon-skeet-facts/9135#9135 ;)
Bobby
I guess this is one of the most commen pitfalls of C-derived languages' expression syntax...
sum1stolemyname
It definitely is an unexpected pitfall and a typical beinner issue. Most common - not sure. But I would say it is guaranteed within the top 10 ;) And the one that most people discover very early.
TomTom
+3  A: 

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.

MrFox
+2  A: 

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.

arscariosus
A: 
using System;

namespace stackOverflow
{
    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");
            var percent = ((Score1 + Score2 + Score3) / 6D);
            Console.WriteLine("Your percentage to date is: {0:00.0}", percent);
            Console.ReadLine();

        }
    } 

}
Ashwani Roy