CS31 You Lu CS31-1K TA
Hello World!
Variable
Out of the Range You input , but it outputs another different number.
I/O cin >> cout <<
Input one word or string cin>>s; //can only input one word, e.g., only my first name. getline(cin, s); //can input the whole string, e.g., my first and last name
cin.ignore(10000, '\n') Use cin.ignore(10000, '\n') after reading a number if the next input will be of a string (using getline)
Arithmatic Division: 5/2=2; 5.0/2=2.5 – as long as one of the number is a “double” we have a “double” division. Mod: 5%2=1 (remainder) Casting: – int a = 2.5 a = ? 2 – (double)5/2 = ? 2.5 – (double) (5/2) = ? 2
Visual Studio 2010 Check the output of compiler to see if there is any warning or error every time.
iostream precision Default is 6 digits If “double a = ”; “cout << a” will only display Here you can use “cout.precision(9)” to set the output as 9 digits. See the example below.
iostream precision Be more careful to use “cout”
header file #include //standard built-in libraries #include “ccc_time.h” //user-defined libraries
if … if (condition) statement; condition: non-zero value means true; zero value means false;
another example
if…else… if (expression) statement; else statement; Nested if statement: if() { if() {…} else {…} } else if() { } else { }
Boolean expression Greater than or equal: “>=“ Less than or equal: “<=” Equal: “==” Not equal: “!=” Logic expression: – AND: && – OR: || – NOT: !
priority Arithmetic operator > relational operator 10 > 1+2 ↔ 10 > (1+2) “ logic operator cout << “true AND false is ” << (true && false);
priority highest! > >= < <= == != && lowest||
while loop while (expression) { statement; } do{ statement; } while (expression)
example
for loop for (initialization; condition; increment) { statement; } infinite loop: for(;;) { }
“continue” skip the current round loop, go to the next round loop for(…) { code 1; code 2; continue; code 3; }
example
“break” stop the current loop and get out of the loop. for (…) { code 1; code 2; break; code 3; } code 4
example
“goto” goto and “lable” must be in the same function. lable: goto [lable];
another example Jump out from a deep nested loop for(…) { for(…) { while(…) { if(…) goto stop; … } stop: cout << “Error in program. \n”; //”break” can only jump out from only one loop
Online reference Some websites are really helpful for you to learn C++, like More detailed reference: Microsoft MSDN library – us/vstudio/hh us/vstudio/hh – us/library/cscc687y(v=vs.80).aspx us/library/cscc687y(v=vs.80).aspx – us/library/3bstk3k5.aspx us/library/3bstk3k5.aspx
Look up “rand()”
My webpage for CS31 1K