Floating-point numbers in C
-
20-06-2021 - |
Question
I'm using the following code to get the output up to 5 decimal characters of any number input by user when divided by 1, I have to typecast it with (float)
.
Can any one tell me how this can be done without typecasting or using float constant?
int main() {
int n;
scanf("%d",&n);
printf("%.5 ", 1/(float)n);
return 0;
}
Solution
You can use this piece of code that uses only integers:
printf(n==1?"1.00000":"0.%05d ", 100000/n);
OTHER TIPS
Taking your question strictly literally, you could do:
int main() {
float n;
scanf("%f",&n);
printf("%.5f", 1/n);
return 0;
}
In this code, there is no float literal and no (float)
cast.
Technically speaking, this should do it:
printf("%.5f ", 1/pow(n,1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow