• We should now be fully online following an overnight outage. Apologies for any inconvenience, we do not expect there to be any further issues.

C++ help.

ThatsABigOne

Diamond Member
Nov 8, 2010
4,422
23
81
I am taking intro class on C++ programming, but I am completely stuck to solve this problem.

Variable declarations are:

char ch = 'E';
int humidity = 21;
int speed = 4;
long rain = 6;
double temperature = 25;

So,
Humidity + Speed will result in "int" and a result value of 25.
Humidity + Temperature will result in "double" and a resulting value of 46.
Temperature + (int) Speed will result in "double" and a resulting value of 29.
(int) Temperature + Speed will result in "int" and a resulting value of 29.
Humidity % Rain will result in double and value of .5

Am I correct about the answers above?

Lastly, I am completely unable to figure out:
ch + speed
(char)(ch + speed) What are resulting type and value?

I appreciate your help in advance.
 

Leros

Lifer
Jul 11, 2004
21,867
7
81
Your first 4 examples look good.

The % (mod) operation gets the integer remainder from the division.
In English, we would say: 11 divide by 5 = 2 remainder 1.

In software, if you're dealing with whole numbers (short, int, long) its very much the same. Divisions with whole numbers always results in whole numbers.
For example:
Code:
int a = 11;
int b = 5;
a / b = 2 (int)
a % b = 1 (int)
If you introduce a double or a float, then you can get fractional results.
For example:
Code:
int a = 11;
double b = 5;
a / b = 2.2 (double)


The general rule of thumb is that arithmetic with two different types, results in the more complex datatype.

int + double = double (because double is more complex than int)
char + int = int (because int is more complex than int)

You can cast to a simpler datatype, but you might end up losing some data.
For example:
Code:
char x = 255;
short y = 1;
x + y = 256 (short)
(char) (x + y) =  0 (char)

In that last example, downcasting to char caused you to lose some data. In that case, we had the short 256 (in binary: 0000 0001 0000 0000). When we cast that to a char, we lose the first 8 bits, leaving us with just 0 (in binary: 0000 0000).
 
Last edited:

ThatsABigOne

Diamond Member
Nov 8, 2010
4,422
23
81
I would like to write Thank You that you made a very informative, and easy to understand answer. With the inclusion of your examples, I am getting a better picture in my mind, of how promotion of data types works.

Thank you!!