550 likes | 666 Vues
More C++ Basics Chapter 3 Lecture CSIS 10A. Agenda. Review C++ Standard Numeric Types Arithmetic–way more than you want! Character (char) data type For Loop Syntax, Run-time and Logical Errors. Review: Standard Program Structure.
E N D
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
Review:Standard Program Structure To solve most problems, your main() program will generally look like this (conceptually) • Declare variables for input, result and intermediate data • Ask for data (cout) • Input data (cin) • Calculate result • Output result (cout)
An interactive C++ program: //circle.cpp Calculate area of a circle // given a radius value #include <iostream> using namespace std; int main() { int area, radius; cout << "enter a radius: "; cin >> radius; area = radius * radius * 3.14; cout << "the area is " << area << endl; return 0; }
A small problem… • Run circle.cpp: • But according to our code, it should be 3.14 • What happened? enter a radius: 1 the area is 3 Press any key to continue . . .
We used the wrong data type! • Go back, change: int area, radius; • To: float area, radius; • Now it works…the lesson? 1) Data types are important! 2) Testing is important!
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
Basic C++ Data Types • int – Represents integers • float – Represents real (floating point) numbers • char – Represents characters (single letters)
Integers only store whole numbers • int a=4; // puts 4 in a • int a=4.579132; // puts 4 in a INTS are great for loop counters, representing inventory, numbers of “things”
Trivia—other integer types uses range of values • short..............(2 bytes)….-32,767 to 32767 • long …….….(4 bytes)…-2 bill to +2 billion • int ………….(depends)…long (sometimes short) • unsigned short (2 bytes)…0 to 65535 • unsigned long ...(4 bytes) …0 to 4 billion
Beware Integer wraparound // wrap.cpp int a, b, c; a = 2000000000; b = 2 * a; c = 3 * a; cout << "b is " << b << endl; cout << "c is " << c << endl; b is -294967296 c is 1705032704
FLOATING-POINT Types float is used to represent numbers with a fractional part such as 2.543 or 6.45 etc… or really big numbers that won’t fit inside ints uses range precision float...........(4 bytes)……10-38 to 1038……..6 digits double…...(8 bytes)……10-308 to 10308…...15 digits long double (10 bytes)....10-4932 to 104932…19 digits
What does floating point mean? Consider a number like 123.45 “Float” the point so that all the digits are on its right (here the point is shifted 3 digits to the left) 123.45 = 0.12345 x 10 3 E-notation: the letter ‘e’= “x10 to the power of” You can actually enter or display data using ‘e’: 123.45 same as 0.12345e3 same as 1.2345e2
Fine…. How is this stored in a float variable ?? The mantissa .12345 and the exponent 3 are stored separately (in a variable) For a 32 bit float type : 23 bit mantissa + 8 bit exponent + 1 sign bit For a 64 bit double type : 52 bit mantissa + 11 bit exponent + 1 sign bit
Implications for Accuracy(round-off error) • A float only stores about 6 digits of mantissa • float PI=3.1415926535897932384626; • PI really contains 3.14159 • float x=50000000000000.0, y=10000.0; • x=x+y; DOES NOT CHANGE X!!! (no room) • Use a double if you need more precision • double PI=3.141592653589793; • About 16 digits of mantissa • double x=50000000000000.0, y=10000.0; • x=x+y; DOES CHANGE X!!! (now there’s room)
Q1) Practice your Scientific Notation (answers at end of slides) • 1234.56 = ____________ x 10 ____ • .03413= ____________ e ____ • 6.78 x 107 = ____________ • 5.32e-5 = ____________
Displaying Floating Point data Output 4.5 -0.375 10.6667 6.78e+07 3308957184 5.23e+11 9.8e-05 cout << 4.5 << endl; cout << -.375 << endl; cout << 10.6666666 << endl; cout << 67800000.0 << endl; cout << 523000000000 << endl; cout << 523000000000. << endl; cout << 0.000098 << endl; This is an integer, no ‘.’
For this to work, #include<iomanip> Formating Floating Point Output cout<<fixed<<showpoint<<setprecision(2); cout << 4.5 << endl; cout << -.375 << endl; cout << 10.6666666 << endl; cout << 67800000.0 << endl; cout << 523000000000 << endl; cout << 523000000000. << endl; cout << 0.000098 << endl; You can use this on problem 8 Output 4.50 -0.38 10.67 67800000.00 3308957184 523000000000.00 0.00
Constants are “variables” -- that never change • Use the keyword “const” in front of declaration • You MUST provide initial value at declaration • const double PI=3.141592653589793; • const double METERS_PER_YARD = 0.9144; • const int MAX=1000; • Now you can say: area = PI * radius * radius; • Don’t over do it: • const int SECONDS_PER_MINUTE = 60; You can use a constant for problem 7
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
Arithmetic in C++ • Basic operations + - * / • Math formulas need to be converted into C++ syntax: FORMULA Equivalent C++ • A = pr2 area=3.14*radius*radius; • F = (v -a) force=(v-a)/(v+a); (v+a)
Arithmetic -- Order of Precedence • * and / are done first, then + and – • Equal levels are done left to right • Example: 3 * 4 + 2 = 14 2 + 3 * 4 = 14 6 + 4 / 2 + 3 = 6 + 2 + 3 = 8 + 3 = 11 • Parentheses have highest precedence (use if you want different order) (6 + 4) / (2 + 3) = 2
Q2) Practice Arithmetic Precedence • Evaluate the following 1+2 * 3 + 4 = _______ 5 + 6 / 2 * 3 = _______ 1 + 2 * (3 + 4) = _______ (7 + 5) / (2 * 3) = _______
Mixed-type Expressions • Expressions involving int and float will give a result of type float (the most inclusive type) • Suppose you have int n; float x; • Then n + x results in float n * 4 results in int n + 4.0 results indouble (4.0 is double) (default for floating pt literals)
Mixed-type Assignments • Assigning int to float is perfectly safe • Assigning float to int may lose fractional part • Suppose you have int n; float x; • Then • x = 15; stores 15 in x • n = 4.5; stores 4 in n -- Compiler Warning! • To satisfy the compiler for (2.) simply explain your intentions:n = int(4.5);
Q3) Can you guess what is stored in these variables? int m, n; double x,y; m = 3.0; n = 12.7; x = m; x = x + 0.5 m = m + 1; y = x + 1;
Integer Division • CAUTION—this is a common C++ error • When both sides are int, the result MUST be int 9 / 2 = 4 9 / 10 = 0 • Sometimes this is what we want • (convert inches to inches and feet) • Usually causes programming errors • When one side is float, the answer is float 9 / 2.0 = 4.5 9.0 / 10 = 0.9
Q4) Can you guess what is stored in these variables? int m, n; double x,y; m = 10 / 3; n = 30 / 7; x = n * m; y = 3 / 4 * x; y = x * 3 / 4; y = (x + 3) / 4;
One more thing…type-casting • If you want to perform floating point division on a pair of integer variables, you can…but you have to temporarily convert one of them to float first: int m=3, n=4; float y; y = float(m) / n; ( y = 0.75) • WRONG y = float(m/n); ( y = 0)
Break Time! • Download Lab2MoreBasics.cpp • Work on problems 1-4, 7,8 • Call me over if you have questions
Remainder % operator • The expression 10 / 3 gives the quotient, 3 • We use 10 % 3 to get the remainder, 1 4 / 3 = 1 12 % 6 = 0 4 % 3 = 1 13 % 6 = ____ 2 / 3 = 0 14 % 6 = ____ 2 % 3 = 2 23 % 7 = _____ Only use % on integers
What good is % operator? • You can use it to subdivide something into hierarchical units: int feet, inches; cout << "Enter inches: "; cin >> inches; feet = inches / 12; inches = inches % 12; cout << feet << " ft. " << inches << " in."; • This is used in things like time, weight, length, change, etc. • Use this slide on Problem 9 Enter inches: 75 6 ft. 3 in.
Arithmetic Assignment Operators • Numeric operators +, -, *, /, % can be combined with the assignment operator = • Saves time and typing • Only when you want to store result in one of operands • a += b a = a + b • a -= b a = a - b • a *= b a = a * b • a /= b a = a / b • a %= b a = a % b
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
CHARACTER types (see Lab3-1) • char……………... (1 byte) • unsigned char…….(1 byte) • A char stores a single letter • What is actually stored is the binary sequence corresponding to a letter’s ASCII code • You can either store a letter, or the numeric code for the letter in a char
Check this out…. #include <iostream.h> void main() { both a and c contain 65 or ‘A’ char a = 65, c = 'A'; cout << “ c = “ << c << endl; cout << “ a = “ << a << endl; } Output….. c = A a = A (in other words, ‘A’ is same as 65)
Character Input • Read 2 chars char grade1, grade2; cin>>grade1>>grade2; cout<<“Grade 1 is ”<<grade1<<endl; cout<<“Grade 2 is ”<<grade2<<endl; NOTE • white space ignored: type AB, A B, A (enter) B same result • Another interesting topic, character escape and control sequences, p 53/54
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
Bored with single execution programs? • Add a for loop to repeat your code several times: for (int k=1; k<=final_value; k=k+1) { statements to repeat }
Example Looped code • Add a for loop to repeat your code several times: int main() { for (int k=1; k<=3; k=k+1) { cout<<“Testing”<<k<<endl; } } Or k++ for short Testing 1 Testing 2 Testing 3
Example Application (for challenge) • Calculate pay for 3 employees: int hrs; double rate; for (int emp=1; emp<=3; emp++) { cout<<“Enter hours & rate: ”; cin>> hrs>> rate; cout<<“Pay = $”<< hrs * rate <<endl; } See p57 to let user determine the number of iterations
Agenda • Review • C++ Standard Numeric Types • Arithmetic–way more than you want! • Character (char) data type • For Loop • Syntax, Run-time and Logical Errors
Types of Errors Syntax: an error in your C++ language/grammar (covered last week) confuses compiler (The dog his paw) forgetting a ; misspelling a variable name datha=3.14; Runtime: when you do something illegal during program execution temp=0.0; rate=1.0/temp; // dividing a number by zero –crash! Logical (or Semantic): When you say something illogical A paw ate his dog. ( Good grammar, illogical meaning) avg = b + c / 2;
Tracking them down • Syntax— • double click on error message, • it takes you to line of code • Look at or above that line for possible errors • Runtime & Logical • You detect them by checking output against test plan • Pinpoint them by displaying variables during intermediate steps (cout) • OR Use debugger to step through program, put watch on variables
That’s a wrap ! • What we learned today: • Data Types • Rules of Arithmetic • For loops • How to debug your program
A1) Answers to Scientific Notation • 1234.56 = 1.23456 x 103 • .03413= 3.413 e -2 • 6.78 x 107 = 67800000 • 5.32e-5 = 0.0000532