Home > Mobile >  C - int arithmetic calculation with float (beginner)
C - int arithmetic calculation with float (beginner)

Time:05-09

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 7 which is type int, 7.0f which is type float or 7.0 which is type double.
  • 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 are int, no promotion occurs, the result will be of type int. This has everything to do with the / operator and nothing to do with where you place the result. The divison will get carried out on int type, so if you wanted it to be type float, it's already too late. Something like float f = input / 7 will not affect the type used by the division in any way. It will only convert the resulting int to float.
  • int input;, input / 7.0f. One operand is type int, the other is type float. The usual arithmetic conversions state that the int operand will get converted to float before 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.)

  •  Tags:  
  • c
  • Related