1 / 81

Capítulo 5 Conditions, Logical Expressions, and Selection Control Structures

Capítulo 5 Conditions, Logical Expressions, and Selection Control Structures. Dale/Weems/Headington. Chapter 5 Topics. Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements

euclid
Télécharger la présentation

Capítulo 5 Conditions, Logical Expressions, and Selection Control Structures

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Capítulo 5Conditions, Logical Expressions,and Selection Control Structures Dale/Weems/Headington

  2. Chapter 5 Topics • Data Type bool • Using Relational and Logical Operators to Construct and Evaluate Logical Expressions • If-Then-Else Statements • If-Then Statements • Nested If Statements for Multi-way Branching • Testing the State of an I/O Stream • Testing a C++ Program

  3. Flujo de Control • El orden en que las instrucciones se ejecutan Cuáles son las posibilidades. . .

  4. Flujo de Control (cont.) • Es Secuenciala menos de que se utilize una estructura de control que lo altere • Existen 2 tipos generales de estructuras de control: “Selection” (también llamado “branching”) “Repetition”(también llamado “looping”)

  5. Data Type bool • El Data type bool es de tipo “built-in”el cual consiste de 2 valores, las constantes true y false • Podemos declarar variables tipo bool bool hasFever; // true if has high temperature bool isSenior;// true if age is at least 55

  6. Estrucutras de control en C++ • Selection if if . . . else switch • Repetition for loop while loop do . . . while loop

  7. Estrucutras de Control Usa expresiones logicas las cuales incluye: 6 Operadores Relacionales < <= > >= == != 3 Operadores Logicos ! && ||

  8. 6 Operadores Relacionales Se usan en expresiones tales como: Expresión AOperatorExpresión B temperature > humidity B * B - 4.0 * A * C > 0.0 abs (number ) == 35 initial!= ‘Q’

  9. int x, y ; x = 4; y = 6; EXPRESIÓN VALOR x < y true x + 2 < y false x != y true x + 3 >= y true y == x false y == x+2 true y = x + 3 7 (true)

  10. En C++ • El valor 0 representa FALSO • CUALQUIER valor que no sea cero representa CIERTO

  11. Comparación de “Strings” • Dos objetos de tipo “string” (o un “string object” y un C “string”) se pueden comparar utilizando los operadores relacionales. • Una comparación carater-por-caracter se va a efectuar utilizando el “character set”de ASCII. • Si todos los caracteres son iguales, entonces los 2 “strings” son iguales. De lo contrario, el “string” con el valor menor en “ASCII” resultaría el “string”menor.

  12. string myState; string yourState; myState = “Texas”; yourState = “Maryland”; EXPRESIÓN VALUE myState == yourState false myState > yourState true myState == “Texas” true myState < “texas” true

  13. Operador Significado Asociatividad ! NOT Right *, / , % Multiplication, Division, Modulus Left + , - Addition, Subtraction Left < Less than Left <= Less than or equal to Left > Greater than Left >= Greater than or equal to Left == Is equal to Left != Is not equal to Left && AND Left || OR Left = Assignment Right

  14. EXPRESIÓN LOGICA SIGNIFICADO DESCRIPCIÓN ! p NOT p ! p es falso si p es cierto ! p es cierto si p es falso p && q p AND q p && q es cierto si ambos p y q son cierto. De lo contrario es falso. p || q p OR q p || q es cierto si cualquiera p o q o ambos son cierto. De lo contrario es falso.

  15. int age ; bool isSenior, hasFever ; float temperature ; age = 20; temperature = 102.0 ; isSenior = (age>= 55) ; // isSenior is false hasFever = (temperature > 98.6) ; // hasFever is true EXPRESIÓNVALOR isSenior && hasFever false isSenior || hasFever true ! isSenior true ! hasFever false

  16. ¿Cuál es el valor? int age, height; age = 25; height = 70; EXPRESSION VALUE !(age < 10) ? !(height > 60) ?

  17. Evaluación “Short-Circuit” • C++ usa la evaluación llamada“short circuit” para expresiones lógicas. • Esto significa que las expresiones lógicas son evaluadas de izquierda a derecha y la evaluación se detiene tan pronto el valor final puede ser determinado.

  18. Ejemplo de “Short-Circuit” int age, height; age = 25; height = 70; EXPRESSION (age > 50) && (height > 60) falso La evaluación se detiene porque el resultado de la expresión && solo es cierta si ambos operandos son ciertos. Por lo tanto ya se puede determinar que la expresión es falsa.

  19. Más “Short-Circuit” int age, height; age = 25; height = 70; EXPRESSION (height > 60) || (age > 40) true La evaluación puede detenerse ahora porque el resultado del operador || es cierto si uno de los operandos es cierto. Por lo tanto ya se puede determinar que la expresión es cierta.

  20. ¿Qué ocurre? int age, weight; age = 25; weight = 145; EXPRESIÓN (weight < 180) && (age>= 20) true Todavía tiene que ser evaluado debido a que no se puede determinar el valor final de la expresión.

  21. ¿Qué ocurre? int age, height; age = 25; height = 70; EXPRESIÓN ! (height > 60) || (age > 50) true false ¿Necesita esta parte ser evaluada?

  22. Escriba una expresión de cada declaración taxRate is over 25% and income is less than $20000 temperature is less than or equal to 75 or humidity is less than 70% age is over 21 and age is less than 60 age is 21 or 22

  23. RESPUESTAS (taxRate > .25) && (income < 20000) (temperature <= 75) || (humidity < .70) (age > 21) && (age < 60) (age== 21) || (age== 22)

  24. Uso de Precedencias int number ; float x ; number != 0 && x< 1 / number / has highest priority < next priority != next priority && next priority ¿ Qué ocurre si number tiene valor cero? Run Time Error (Division by zero)

  25. Beneficios del “Short-Circuit” • Una expresión “Boolean” se puede poner primero para “velar” una operación potencialmente no segura en una segunda expresión “Boolean” • Se ahorra tiempo en la evaluación de expresiones complejas usando los operadores || y&&

  26. Nuestro Ejemplo Revisado int number; float x; ( number!= 0) && ( x < 1 / number ) se evalúa primero y tiene valor falso Debido a que el operador es &&, la expresión completa ya es falsa y el lado derecho no se evalúa.

  27. Precaución sobre Expresiones en C++ • “Boolean expression” es una expresión cuyo resultado es cierto o falso • Una expresión es cualquier combinación válida de operadores y operandos. • Cada expresión tiene un valor • Esto te puede llevar a resultados inesperados • Construye las expresiones con cuidado • Se recomienda el uso de paréntesis • De lo contrario utiliza el “precedence chart” para determinar el orden.

  28. ¿Qué hay mal? Se supone que muestre el mensaje “HEALTHY AIR” si la calidad del aire está entre 50 y 80. Pero cuando se prueba con 35, sale el mensaje “HEALTHY AIR” cuando no debería salir. int AQIndex ; AQIndex = 35 ; if (50 < AQIndex < 80) cout << “HEALTHY AIR“ ;

  29. Análisis de la Situación AQIndex = 35; De acuerdo al “precedence chart”, la expresión (50 < AQIndex < 80) significa (50 < AQIndex) < 80 porque < es “Left Associative” (50 < AQIndex) es falso (genera valor 0) (0 < 80) es cierto

  30. Versión Corregida int AQIndex ; AQIndex = 35 ; if ( (50 < AQIndex) && (AQIndex < 80) ) cout << “HEALTHY AIR“ ;

  31. ComparandoValores Tipo float • No se debe comparar valores flotantes por igualdad sino por “near-equality”. (casi-igualdad) float myNumber; float yourNumber; cin >> myNumber; cin >> yourNumber; if ( fabs (myNumber - yourNumber) < 0.00001) cout << “They are close enough!” << endl;

  32. Flujo de Control • Orden en el cual las instruciones son ejecutadas. LAS 3 POSIBILADES SON: Secuencial “Selection Control Structure” “Loop Control Structure”

  33. “Selection statements” Son usadas para escoger una acción dependiendo de la situación del programa según se ejecuta.

  34. Estructuras de Control Utilizan expresiones lógicas que podrían incluir: Operatores Relacionales (6) < <= > >= == != Operadores Lógicos (3) ! && ||

  35. En C++ El valor 0 representa FALSO Cualquier valor no-cero representa CIERTO

  36. ¿Qué puede estar mal aquí? float average; float total; int howMany; . . . average = total / howMany;

  37. Versión Mejorada float average; float total; int howMany; if ( howMany> 0 ) { average=total/howMany; cout << average; } else cout <<“No prices were entered”;

  38. Syntaxis del If-Then-Else if ( Expression ) StatementA else StatementB NOTA: StatementA y StatementB pueden ser una sola instrucción, un “null statement”, o un bloque.

  39. if ... else provee una selección “two-way” Al ejecutar una de 2 clausulas (la clausula if (then) o la clausula else) TRUE FALSE expression if clause else clause

  40. Se recomienda el uso de bloques if ( Expression ) { } else { } “if clause” “else clause”

  41. int carDoors, driverAge; float premium, monthlyPayment ; . . . if ( (carDoors== 4 ) && (driverAge > 24) ) { premium = 650.00 ; cout << “ LOW RISK “ ; } else { premium = 1200.00 ; cout <<“ HIGH RISK ” ; } monthlyPayment = premium / 12.0 + 5.00 ;

  42. ¿Qué ocurre si se omiten las llaves? if ( (carDoors== 4 ) && (driverAge > 24) ) premium = 650.00 ; cout << “ LOW RISK “ ; else premium = 1200.00 ; cout <<“ HIGH RISK ” ; monthlyPayment = premium / 12.0 + 5.00 ; COMPILE ERROR OCCURS.The “if clause” is the single statement following the if.

  43. Las llaves se omiten únicamente cuando cada clausula sea una sola instrucción if ( lastInitial <= ‘K’ ) volume = 1; else volume = 2; cout << “Look it up in volume # “ << volume << “ of NYC phone book”;

  44. Determinar dónde la primera ‘A’ se encontro en un “string” string myString ; string::size_type pos; . . . pos = myString.find(‘A’); if ( pos == string::npos ) cout << “No ‘A’ was found“ << endl ; else cout << “An ‘A’ was found in position “ << pos << endl;

  45. Quizz - If-Then-Else para una orden por correo Asigna el valor .25 a discountRate y asigna el valor 10.00 a shipCost si purchase es mayor de 100.00 De lo contrario, asigna el valor .15 a discountRate y asigna de valor 5.00 a shipCost Independientemente, hay que calcular totalBill

  46. Las llaves no pueden ser omitidas if ( purchase > 100.00 ) { discountRate = .25 ; shipCost = 10.00 ; } else { discountRate = .15 ; shipCost = 5.00 ; } totalBill = purchase * (1.0 - discountRate) + shipCost ;

  47. “If-Then statement” es una selección En esa selección se determina si ejecutar o no un “statement” (el cual puede ser una sola instrucción o un bloque entero) CIERTO expression FALSO statement

  48. Syntaxis del “If-Else” if ( Expression ) Statement NOTA: “Statement” puede ser una sola instrucción, un “null statement”, o un bloque.

  49. Terminando el programa intnumber ; cout << “Enter a non-zero number ” ; cin >> number ; if (number == 0 ) { cout << “Bad input. Program terminated ”; return 1 ; } // otherwise continue processing

  50. Estos son equivalentes. ¿Porqué? if (number==0 ) if ( ! number ) { . { . . . . . . . } } Cada expresión solo es cierta cuando el número no tiene valor 0.

More Related