I’m fairly new to programming in general but have been working with Java for the past 2-3 months and decided to take a crack at C# on the side just for fun because I heard they were similar. The problem I’m having with this program, which is just a way for someone to convert an int to a percentage, is that it takes all my input correctly but the percentage always shows up as zero! For example, there are two input prompts: one that asks you for a number for converting and one that asks you what the number is out of. After both prompts the program displays correctly “Your percentage is: ” and then just writes 0 no matter what numbers I use for input, help please!
[code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumToPercentage
{
class Program
{
static void Main(string[] args)
{
int userScore, userTotalScore, userPercentage;
string userInput, userTotal;
Console.WriteLine("Welcome to the number to percentile conversion program!");
Console.WriteLine("Please enter your number here: ");
userInput = Console.ReadLine();
userScore = int.Parse(userInput);
Console.WriteLine("Please enter what the number is out of (i.e. 100, 42, 37, etc.): ");
userTotal = Console.ReadLine();
userTotalScore = int.Parse(userTotal);
userPercentage = (userScore/userTotalScore)*100;
Console.WriteLine("Your percentage is: " + userPercentage);
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
[/code]
The problem is integer math, it rounds towards zero.
Convert at least one of the operands to a floating point type (double, float, decimal) when you perform your calculation.
If needed, you can always cast the result back to an integer if you are uninterested in the decimal places.