Mar 17, 2014 at 10:29am UTC
Hi Guys,
I just started´my class this week and I have a simple question!
What is the code for calculating a percentage of a number? For example:
Balance: $1000
Rate: 4,2%
Result: $42
Any and all help is greatly appreciated! Thank you!
Mar 17, 2014 at 10:37am UTC
Easy way: Do it like in maths. You have a number: Multiply by the percentage / 100. For example:
Balance: $1000
Rate: 4.2%
Result = 1000 * (4.2 / 100) = 42
Now you can put it in code (I'm assuming this is homework)
Mar 17, 2014 at 10:37am UTC
value / 100 * percentage = 4.2% of value
Mar 17, 2014 at 10:39am UTC
That easy huh! Thank you guys! =)
Mar 17, 2014 at 10:50am UTC
OK here it goes....
So I made an attempt to write this in code and it did not work! The ruselt came to: 0 when ´running the program!
Balance: $1000
Rate: 4,2%
Result: $42
1 2 3 4 5 6 7 8 9 10 11
cout << "Enter deposit amount!" ;
int deposit;
cin >> deposit;
int rate;
cout << "Enter your rate!" ;
cin >> rate;
int result = deposit * (rate/100);
cout << result
Last edited on Mar 17, 2014 at 10:59am UTC
Mar 17, 2014 at 10:58am UTC
The problem is that you're using integer arithmetic. (rate/100)
is being rounded down to 0.
You need to use floating-point types, not integers.
Oh, and you end a code block with [/code], not [code]. It's easier if you use the buttons to the right of the editor :)
Mar 17, 2014 at 11:01am UTC
Yes sorry about the [/code]...
I changed int to float and it worked perfect!
Thanks again all!!
Mar 17, 2014 at 11:05am UTC
You're welcome! Glad it worked :)