No percentage calculation | Sololearn: Learn to code for FREE!

+1

No percentage calculation

Pls anyone try C# End of Project Application. I got absolutely no clue how to calculate 10 or whatever is entered as discount percent % of the value. Isn't it value / 100 * discount to get the value of [dicount]%??? I learned it in school like that. Why is C# unable to calculate?

c#

1/25/2021 11:20:27 PM

Tom Schneider

9 Answers

New Answer

+1

You are using integer division, hence the 0 you are getting. You can use casting to use a different numeric division. Even if value is a double, integer division will still take place. Because 100 is read as an int by the compiler. You can tell the compiler that it's a double by appending a "D" to the end. (or use casting) So, value / 100D * discount.

+1

The correct way should be discount / 100 * value.

0

I'll try that... I always got rewarded with a wonderful zero until now... Let's see.

0

Alright no problem.

0

Still my variable totalDiscount to be subtracted from the value remains 0, so the values stay as they are.

0

I am already using double as variable type for the totalDiscount variable, to be sure he can calculate with values like 0.5 which would be 1% of 50 and then multiply with discount (10 in the first case) to return 2 (after casting to Int32 explicitly)

0

0shibka I tried that... Overall, the problem is the following: In this test, you get a Dictionary with strings (coffee names) as keys and integers (prices) as values. The job is to iterate through the whole thing and apply a discount (varying input, 3 test cases, 1 of the hidden) on each price. Afterwards, the whole Dictionary has to be printed. I always solved problems in Programs anyhow, but this time, as C# is simply refusing to do its job, I'm quite done because it's the last test to get the certificate...

0

static void Main(string[] args) { int discount = Convert.ToInt32(Console.ReadLine()); Dictionary<string, int> coffee = new Dictionary<string, int>(); coffee.Add("Americano", 50); coffee.Add("Latte", 70); coffee.Add("Flat White", 60); coffee.Add("Espresso", 60); coffee.Add("Cappuccino", 80); coffee.Add("Mocha", 90); //your code goes here } } }

0

Adam McGregor thanks to your tip and a lot of knowledge I fixed it with a nice workaround. The problem that occurred after casting into Double was, that he sometimes rounded to the wrong number. I used Math.Floor() to fix. For real, this isn't designed to be solved by anyone without a good knowledge and experience in Java/C#...