Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply float with integers in C?

When I execute this code it returns me 1610612736

void main(){
float a=3.3f;
int b=2;
printf("%d",a*b);
}

Why and how to fix this ?

edit : It's not even a matter of integer and float, if i replace int b=2: by float b=2.0f it return the same silly result

like image 449
Wicelo Avatar asked Jun 12 '13 04:06

Wicelo


People also ask

What happens if you multiply an integer with a float?

The result of multiplying a float and an integer is always going to be a float. Copied! You can use the round() function if you need to round the result to N digits precision after the decimal point.

How do you multiply float values?

Program to Multiply Two Numbersprintf("Enter two numbers: "); scanf("%lf %lf", &a, &b); Then, the product of a and b is evaluated and the result is stored in product . product = a * b; Finally, product is displayed on the screen using printf() .

Can you multiply floats?

First off, you can multiply floats. The problem you have is not the multiplication itself, but the original number you've used. Multiplication can lose some precision, but here the original number you've multiplied started with lost precision. This is actually an expected behavior.

Can we assign integer value to float in C?

Assigning an integer to float and comparison in C/C++Float is a data type used to define a number that has a fractional value. These can have decimals also. Now, we will check what will be the value of float and integer return by the compiler when we input the same value for both.


2 Answers

The result of the multiplication of a float and an int is a float. Besides that, it will get promoted to double when passing to printf. You need a %a, %e, %f or %g format. The %d format is used to print int types.

Editorial note: The return value of main should be int. Here's a fixed program:

#include <stdio.h>

int main(void)
{
    float a = 3.3f;
    int b = 2;
    printf("%a\n", a * b);
    printf("%e\n", a * b);
    printf("%f\n", a * b);
    printf("%g\n", a * b);
    return 0;
}

and its output:

$ ./example 
0x1.a66666p+2
6.600000e+00
6.600000
6.6
like image 93
Carl Norum Avatar answered Oct 08 '22 04:10

Carl Norum


Alternately, you could also do

printf("%d\n", (int)(a*b));

and this would print the result you're (kind of) expecting.

You should always explicitly typecast the variables to match the format string, otherwise you could see some weird values printed.

like image 42
krthkr Avatar answered Oct 08 '22 02:10

krthkr