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("Ente开发者_如何学运维r 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();
}
}
}
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;
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.
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.
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();
}
}
}
精彩评论