We will discuss these in class. Complete the exercise with a partner, taking turns suggesting things you notice that might be improved.
Do not copy-and-paste into your editor; just read the code and think!
How can each of these C++ code segments be improved?
Code 1
CPP
// How can this code be improved?
const int TARGET_TEMPERATURE = 20;
int temperature = 0;
print("What is the current temperature? ");
cin >> temperature;
if (temperature <= 0) {
println("It's freezing!");
int difference = TARGET_TEMPERATURE - temperature;
println("To be perfect, the temperature should change by {} degrees!", difference);
} else {
println("It's thawed!");
int difference = TARGET_TEMPERATURE - temperature;
println("To be perfect, the temperature should change by {} degrees!", difference);
}
Code 2
CPP
// How can this code be improved?
int numVaccinesNeeded = 0;
print("How many vaccines are needed? ");
cin >> numVaccinesNeeded;
if (numVaccinesNeeded > 1000) {
string message = "Critical shortage";
} else {
string message = "Supply OK";
}
println("{}: Order {} more vaccines.", message, numVaccinesNeeded);
// Hint: This won't compile. Why?
Code 3
CPP
// How can this code be improved?
double percent = 0;
print("Enter nurse's test score: ");
cin >> percent;
if (percent < 75.0)
println("Please have them retake the test later.");
else
println("Well done!");
println("Issue them a renewed license.");
Code 4
CPP
// How can this code be improved?
double microLoan = 0;
print("How much is needed for the micro loan? $");
cin >> microLoan;
if (microLoan < 0) {
println("Loan value must be > $0.00");
}
if (microLoan > 100) {
println("Loan value must be <= $100.00");
} else {
println("Loan approved.");
}
Code 5
CPP
// How can this code be improved?
double bodyTemp = 0;
print("Enter patient's body temp ('C): ");
cin >> bodyTemp;
if (bodyTemp <= 37.0) {
println("Temperature normal");
}
if (bodyTemp > 37.0) {
println("Elevated temperature");
}
Code 6
CPP
// How can this code be improved?
int age = 0;
print("Enter your age: ");
cin >> age;
if (age < 12) {
println("I'm sorry, you can't enter this ride.");
} else if (age > 100) {
println("You may want to rethink this!");
} else {
println("Welcome!");
}