I have user integer input input and wanted to output the calculation with the input by division. The return had been 0 rather than decimals results. Wanted to prevent use of initialize the variable input with int rather than float to prevent possible errors in later data input with delimiter .
Is there any way to calculate float result w/ int input other than assigning float for the variable input ?
Source:
#include <stdio.h>
#include <stdlib.h>
int main() {
int input;
printf("Enter data:");
scanf("%d", &input);
printf("Output: %f", (input / 7);
return 0;
}
Return:
Input: 6
0.0000
CodePudding user response:
You need input/7 to be performed with floating point math, rather than integer math.
Like this...
printf("Output: %f", (input / 7.0f));
This link explains a bit better how C/C deals with mixing floats/doubles/ints etc. Does one double promote every int in the equation to double?
CodePudding user response:
- Everything in C has a type, including constants like
7which is typeint,7.0fwhich is typefloator7.0which is typedouble. - Whenever mixing fixed point and floating point operands in the same operation with two operands (generally a bad idea), then the fixed point operand is converted to floating point. This is called "the usual arithmetic conversions".
Examples:
int input;,input / 7. Both operands areint, no promotion occurs, the result will be of typeint. This has everything to do with the/operator and nothing to do with where you place the result. The divison will get carried out oninttype, so if you wanted it to be typefloat, it's already too late. Something likefloat f = input / 7will not affect the type used by the division in any way. It will only convert the resultinginttofloat.int input;,input / 7.0f. One operand is typeint, the other is typefloat. The usual arithmetic conversions state that theintoperand will get converted tofloatbefore the division. So this would solve the problem.
However, here is a better idea: Simply never mix fixed point and floating point in the same expression, because the potential for bugs is huge. Instead do this:
scanf("%d", &input);
float f_input = (float)input;
printf("Output: %f", (f_input / 7.0f);
Now nothing goes on implicitly, all implicit conversions have been removed. The cast is not necessary, but creates self-documenting code saying: "yes I do mean to make this a float type rather than had it happen by chance/accident".
(Advanced topic detail: printf actually converts the passed float to double, but we need not worry about that.)
