+ 1
A problem in my c code
#include <stdio.h> int main() { int houses; int percentage; scanf("%d", &houses); percentage = (2/houses)*100; printf(" %d", percentage); return 0; •why does it prints for me 0 ?!
8 Respuestas
+ 5
In C, a/b = 0 when a<b and a,b are integers.
Try using floats instead
+ 4
printf("%f",percentage);
If you want to get an integer output, try using ceil() or floor() as you expected.
0
What if i wanted only whole numbers in my output as percentage ?
0
Simba
#include <stdio.h>
int main() {
float houses;
float percentage;
scanf("%f", &houses);
percentage = (2/houses)*100;
printf(" %d", percentage);
return 0;
}
Now when houses = 3 it gives me percentage=1. Why ?
0
You may try typecast the division:
percentage = (float)2/houses*100
don't forget to use "%f" instead of "%d" in printf() in the final answer
0
I found two interesting options and both uses typecasting:
Integer percentage:
#include <stdio.h>
int main(void) {
int houses;
int percentage;
scanf("%d", &houses);
percentage = (float)2/houses*100;
printf("%d", percentage);
}
Float percentage:
#include <stdio.h>
int main(void) {
int houses;
float percentage;
scanf("%d", &houses);
percentage = (float)2/houses*100;
printf("%f", percentage);
}
In the second option you need only to change type of percentage (float percentage) and of course use "%f" in final printf().
Tip: for typecast you must avoid round brackets ( ) see the code.
0
If you prefer not use typecasting, define percentage as float and use 2.0 instead of 2 in the division. Hope I helped ;)
0
Thankyou.🤝