Using the book Ivor Horton's Beginning Visual C++ 2008.
Chapter 2, pages 76-77 - Rules for Casting Operands
Using Microsoft Visual Studio 2008 Pro
I understand the basic of how this casting works in theory. But I tried to write a program to express this example and make it clearer to myself. And also to practice a little too. But my output is not what it should be. I have to be doing something majorly stupid here. Can someone help explain what I have done wrong?
His example is:
1 2 3 4 5 6
|
double value(31.0);
int count(16);
float many(2.0f);
char num(4);
value = (value - count)*(count - num) / many + num / many;
|
Now work out what casts the compiler will apply in the exicution of the statement.
When I work everything out in my head or on paper the result is a double value of 92.0
Here is my problem. I have rewrote this several times to find my fault with no luck.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
//Ex2_casting.cpp
//Example of how casting works with mathmatical operations
#include <iostream>
using namespace std;
int main()
{
double value(31.0);
int count(16);
float many(2.0f);
char num(4);
value = (value - count)*(count - num) / many + num / many;
cout << endl << "The answer is: " << value << endl;
double value2;
value2 = value - count; //(value - count)
cout << endl << "double value - int count = double value: " << value2 << endl;
int value3;
value3 = count - num; //(count - num)
cout << endl << "int cout - char num = int value: " << value3 << endl;
double value4;
value4 = value2 * value3; //(value - count) * (count - num)
cout << endl << "double value * int value = double value: " << value4 << endl;
double value5;
value5 = value4 / many; //(value - count)*(count - num) / many
cout << endl << "double value / float num = double value: " << value5 << endl;
float value6;
value6 = num / many; // num / many;
cout << endl << "char num / float many = float value: " << value6 << endl;
double value7;
value7 = value5 + value6; //(value - count)*(count - num) / many + num / many
cout << endl << "double value + float value = double value: " << value7 << endl;
return 0;
}
|
My output is:
The answer is: 92
Correct
double value - int count = double value: 76
int cout - char num = int value: 12
double value * int value = double value: 912
double value / float num = double value:
char num / float many = float value: 2
double value + float value = double value: 458
Where did I go wrong? Am I just doing the mathmatical calculations wrong? Or is this an error with my varible choices? Or something else?