Member Avatar for chudapati09
result = number1 / number2;

I am new to C++, but I have some knowledge in Java.
What my program does is, the program asks the user two numbers. The user could only select, one, two, or zero. Then the user would select an arithmetic operator: plus, minus, times, divide. I figured everything out except the division part.
When the user select one divide by two, the answer should come out as 0.5, but it comes out as 0. All three variables are int values, so I would need to convert them into a float or a double. But how would I cast them? I've tried doing this, float(number1), and many more similar to that, but it wouldn't work.

Thanks,
Sam

Sam,
dividing integers truncates the decimal part, one or both of them should be float/double depending on precision of data.

int a, b, sum;//all are ints so the decimal part is truncated
a=10;
b=3;
sum=a/b; //gives 3, truncates the repeating decimal

int c;
double d;
double sum2;
c=10;
d=3.0;
sum2 = c/d; // gives 3.33333.........

double x, y, z;
x=10.0;
y=3.0;
z=x/y; //gives same 3.3333333333..............
Member Avatar for chudapati09

Sam,
dividing integers truncates the decimal part, one or both of them should be float/double depending on precision of data.

int a, b, sum;//all are ints so the decimal part is truncated
a=10;
b=3;
sum=a/b; //gives 3, truncates the repeating decimal

int c;
double d;
double sum2;
c=10;
d=3.0;
sum2 = c/d; // gives 3.33333.........

double x, y, z;
x=10.0;
y=3.0;
z=x/y; //gives same 3.3333333333..............

Sorry I didn't respond back. But I figured out what was happening, it actually was stupid.
The variable result was an integer, so even if i did cast it as a float or a double the end result would have been an integer.

This is what my mistake looked like:

int result;
int number1 = 5;
int number2 = 2;

result = number1 / number2;

This is what my code looked like after I fixed it:

float result;
int number1 = 5;
int number2 = 2;

result = float(number1) / number2;
Member Avatar for chudapati09

Mark it then solved :)

Sorry but I'm new here, and I don't know how to mark a thread solved. Would you or someone else mind telling me how? Thanks.

At the bottom you will find:

Has this thread been answered?
If this thread has been successfully resolved, please Mark this Thread as Solved so that it can be added to our Knowledge Base and help others. Also, posters who replied appreciate knowing that they were helpful.

Click link contained and voila.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.