+ 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?

25th Jan 2021, 11:20 PM
Tom Schneider
9 Réponses
+ 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.
26th Jan 2021, 11:12 AM
Adam McGregor
+ 1
The correct way should be discount / 100 * value.
25th Jan 2021, 11:27 PM
africana
africana - avatar
0
I'll try that... I always got rewarded with a wonderful zero until now... Let's see.
25th Jan 2021, 11:28 PM
Tom Schneider
0
Alright no problem.
25th Jan 2021, 11:29 PM
africana
africana - avatar
0
Still my variable totalDiscount to be subtracted from the value remains 0, so the values stay as they are.
25th Jan 2021, 11:30 PM
Tom Schneider
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)
25th Jan 2021, 11:32 PM
Tom Schneider
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...
25th Jan 2021, 11:41 PM
Tom Schneider
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 } } }
25th Jan 2021, 11:42 PM
Tom Schneider
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#...
26th Jan 2021, 9:09 PM
Tom Schneider