# Arithmetic conversions

• 10-02-2005
wilksdr
Arithmetic conversions
Hi all,

Im a beginner with no previous programming experience. Anyway, Im taking an online course in ANSI C programming, and need some help.

This is a test question, and Im not asking for the answer. Just some help in a way for me to find/understand the answer.

the question is:

Given the following declarations and initialization:

int i = 1;
int x = 2.0;

What is the value and type of the expression i/x ?

My book explains usual arithmatic conversions, and it says:

"if either operand is of type double, the other operand is converted to double."

I wrote a sample program to see how the computer evaluates this.

Code:

```#include <stdio.h> int i = 1; int x = 2.0; int y; int main(void) {         y=i/x;         printf("y = %d as decimal", y); return 0; }```
When I run this I get 0 as result, however when I run:

Code:

```#include <stdio.h> int i = 1; int x = 2.0; int y; int main(void) {         y=i/x;         printf("y = %f as float", y); return 0; }```
I get a runtime error.

Any suggestions that I could try to help me understand this better?

Thanks,

Darren
• 10-02-2005
rockytriton
you need to use floats for your types if they aren't integers. Change all your "int"s to "float"
• 10-02-2005
grumpy
Two pointers;

1) With the initialisation "int x = 2.0;", what value do you expect x to wind up with. And what type is it?

2) The reason for a runtime error in your second code example is that you're passing an int (y) to printf() which has been told to expect a double. Using the %f specifier doesn't magically turn y into a double.
• 10-02-2005
cwr
With:
Code:

```int i = 1; int x = 2.0;```
Both variables are of type int. Just because you used 2.0 doesn't make it a floating point type. The 2.0 will be converted to an int because x is an int. Therefore, when you do a division, you are just doing an integer divide, since neither type is a float or double.

With your printf, you are trying to print an integer variable (y) using the %f double format specifier. This doesn't make any sense, so you must use %d, or cast the y to a double.

Of course, you will still get an output of 0, because y is an int type, but at least it will work. Even if you change y to be a double type, you will still get 0, because both the other variables are ints.
• 10-02-2005
wilksdr