Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Beginner Question on C program: division of integer variables

Status
Not open for further replies.

emb

Newbie level 4
Joined
Jul 14, 2015
Messages
6
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Activity points
59
Hello experts,

I wrote the following lines of code in C:

Code:
int32_t num = 10267846;
int32_t den = 833;
float   div_result;

div_result = num / den;

I expected a value of some floating point type, but I am always getting 0 instead.

Please help me if there is anything wrong with my code and understanding.

Thanks.

IDE: Eclipse IDE for C/C++ Dev
MCU: STM32F3 series
 

Why not you also declare both dividend and divisor as float type ? It is notorious that some undesirable type casting are being performed. If your problem is regarded to lack of dinamic memory, you could put that within a function.
 

I expected a value of some floating point type, but I am always getting 0 instead.
Yes, 100 % expectable.

You may want to review a C text book about automatic type conversion involved with arithmetic expressions. In this case, language rules require that an integer division is performed and then the quotient converted to float. To perform a float division, at least numerator or denominator must be casted to float before. E.g.
Code:
div_result = (float)num / den;
 

The rule is as follows:

the variable types follow a certain precedence: float is having higher precedence than int; int is having higher precedence than bool.

operands on the right are grouped as per the evaluation rule.

A group is evaluated as per the highest type in the group.

Finally the result is converted to the type of the variable on the left side.
 

I totally agree with c_mitra.

I do not see any reason that the OP code could not work properly if there weren't those int32_t. I do not know how DEV compiler works but in Microsoft Visual Studio int32_t is not defined.

Anyway, if changing "int32_t" with just "int" it works perfectly as expected. 10267846/833=12326.34574 but because of that int division in the "float" will be stored 12326.00000.
 

Yes you are right, I didn't look at the input numbers.

The shown expression gives 12326.0000, if one argument is casted to float it gives 12326.34573829.
 

It is indeed strange that it doesn't give the results as expected, but a good rule is to always use cast in order to avoid unpleasant surprises like this one.
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top