CS 150 Introduction to C++ Programming - Spring 1998 

[ Home | Lecture Notes| WebTutor | WebTutor Site Map]


Numbers: float/int


C++ supports two basic number types:

There are variations of these numbers to get bigger or smaller versions.

Mostly you will just use "int" and "float" as appropriate.
Floating point and integer numbers have different rules for thier arithmetic.
In particular dividing an integer by an integer produces an integer (called integer divide ) by simply removing the part after the decimal point (called truncating to an integer). Also integers have a way of producing the remainder of the division as a integer called the modulus operator (written as "%"). This operator does not work for floats. (see tutor page on evaluating expressions for more examples)

It is possible to mix integers and floating points numbers. Such expressions are called mixed type or mixed mode expressions. In such cases, all numbers are converted to floating point number and the result is a floating point number. Such a conversion is called implicit since it is done automatically.
You can also force a conversions to occur explicitly by using a type cast operator. (pp. 97-98).

This exercise tests your understanding of mixed mode expressions.

Given the statements: (adapted from the program lab3e1.cpp)

	int g1,g2,g3,g4;
	float avg;
	int iavg;
	g1 = 86; g2 = 56; g3 = 75, g4 = 98; // it is OK to put more than one statement on a line

What will be the value assigned for each of the following statements?

  1. avg = (g1 + g2 + g3 + g4)/4;

  2. avg = (g1 + g2 + g3 + g4)/4.0;

  3. avg = float(g1 + g2 + g3 + g4)/4;

  4. avg = float(g1 + g2 + g3 + g4)/4.0;

  5. iavg = float(g1 + g2 + g3 + g4)/4.0;

 

Choose one when done
   

Copyright chris wild 1998.
For problems or questions regarding this web contact [Dr. Wild (e-mail:wild@cs.odu.edu].
Last updated: March 08, 1998.