cs31 lecture 3

2 foo has value 36 float foo 12 242 foo has value

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ample: foo = 12 + 24.2; x The type of the expression depends on the type of the The <lhs> <lhs> Example: int foo = 12 + 24.2; // foo has value 36 float foo = 12 + 24.2; // foo has value 36.2 x Be careful: floats are truncated to int, not rounded Example: int foo = 12 + 24.9; // foo has value 36 23 Integer division x Be careful: if division is used on integer data (variable or Be value), then integer division is used value), x Example: int foo = 3; foo = foo / 4; // foo has value 0 x Problem arises also for values Problem Example: float foo = 3 / 4; // foo has value 0 24 Integer division x To avoid the problem with values Add .f at the end of the number, to instruct the compiler to treat it Add as a float as • Example: float foo = 3.f / 4.f Add .0 at the end of the number to make it decimal • Example: float foo = 3.0 / 4.0 25 Common mistakes x Forgetting to declare a variable Forgetting The compiler tells you the error x Read the value of a variable before setting it Read The compiler *may* tell you the error IIn this case, the value of the variable at its first use is n undetermined undetermined x Use a type too small to hold the data The compiler usually doesnt tell anything x Make a mistake with integer division The compiler doesn’t tell you anything 26 A few examples 27 A first problem: compute the mpg of a car Algorithm MPG: IInput: nput: • m: number of miles since last refuel • g: number of gallons consumed since last refuel Output: • mpg: miles per gallon achieved 1.mpg := m / g 2.return mpg return 28 Now in C++ float MPG(float m, float g) { float mpg = m / g; float return mpg; return } int main() { float mpg = MPG(42, 10); float std::cout << “My mpg: “ << mpg << std::endl; std::cout } 29...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online