C++ coding issues | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

C++ coding issues

Could someone tell me why the result is always 0%, no matter what numbers I give?? #include <iostream> using namespace std; int main() { unsigned int a,b; float c; cout << "Give the number of people"<< endl ; cin >> a; cout << "Give the number of students"<<endl; cin >> b; c=(b/a)*100; cout << "The percentage of students among the public is: " << c << "%"; }

5th Sep 2017, 12:14 PM
Christos Provopoulos
6 Answers
+ 4
c=b*100/a; Division in C++ always is a integer so in the order you coding, always is / by a number bigger than up so naturally result is 0.something and that division result is a integer so then 0
5th Sep 2017, 12:31 PM
Daniel
Daniel - avatar
+ 9
u should make either a or b into a double or float before dividing them
5th Sep 2017, 12:21 PM
Vahid Shirbisheh
Vahid Shirbisheh - avatar
+ 2
If b<a and a, b are integers then b/a would always be 0. The efficient way to solve this is not to use floats, but rather replace c = (b/a) *100; with c = b*100/a; This way you multiply first, then divide (assuming you won't overflow) Even more, if you want your answer to be more correct, use: c = (b*100+50)/a; Because otherwise if your answer would have been 12.99% with floats, you would still get 12% with integers. By adding 50 above, you round your result to the nearest 1%
5th Sep 2017, 12:33 PM
Udi Finkelstein
Udi Finkelstein - avatar
+ 1
that's wrong division doesn't always result in division but division btw integers is always integer try type casting or make a and b float.
5th Sep 2017, 6:17 PM
Himanshu Dubey
Himanshu Dubey - avatar
0
Thanks guys. Actually I forgot that in C++, division is always returning an integer value. So, here is always 0.
5th Sep 2017, 3:01 PM
Christos Provopoulos