ACCIS Online Portfolio
Beginning C++ Assignment 2
Graded by John Webb
71/72 = 97%
Janine, please read my comments below:
Name: Janine Bouyssounouse
Student ID: 4782181
E-mail: jcbouyss@yahoo.com
Course Number: CS110
Course Code: 03A2
Assignment Number: 2
Compiler Version: CodeWarrior 9
Version of Word: 2002
4.1 Write a program that reads two floating-point values representing angles and displays a
message stating which angle has the greater tangent value.
// -------------------------------------------------------------
// Program CS110ques4_1
//
// Purpose: Reads two floating point values representing angles
// and displays a message stating which one has the
// greater tangent value.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
#include
using std::setprecision;
using std::fixed;
#include
using std::tan;
void showPurpose();
float getFloat();
float determineLargestTan(float a, float b);
void showResults(float a, float b, float l);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for the measure of two angles,\n";
cout << "determine the highest tangent value and display this.\n\n";
}
float getFloat()
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: A float is returned.
// ------------------------------------------------------------
{
float f;
cout << "Enter an angle as a floating point: "; // prompt
cin >> f; // read an integer
return f;
}
float determineLargestTan(float a, float b)
// ------------------------------------------------------------
// Preconditions : a, b are set to floating point angles
// to find the largest tangent value.
// Postconditions: The largest angle is returned.
// ------------------------------------------------------------
{
float h;
h = a;
if(tan(b) > tan(h))
h = b;
return h;
}
void showResults(float a, float b, float l)
// -----------------------------------------------------------
// Preconditions : a and b are set to the angles
// l is set to the largest tangent value
// Postconditions: Displays the angles and states the largest
// tangent value.
// -----------------------------------------------------------
{
cout << setprecision(2) << fixed;
cout << "\nThe two angles entered were " << a << " and " << b <<"\n";
cout << "The largest tangent value is for the angle " << l << "\n";
cout << "The tangent value for this angle is " << tan(l) << endl;
}
// function main begins program execution
int main()
{
float one; // first angle to be input by user
float two; // second angle to be input by user
float largest; // variable in which the highest integer will be stored
showPurpose();
one = getFloat();
two = getFloat();
largest = determineLargestTan(one, two);
showResults(one, two, largest);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for the measure of two angles,
determine the highest tangent value and display this.
Enter an angle as a floating point: 1
Enter an angle as a floating point: 3.14
The two angles entered were 1.00 and 3.14
The largest tangent value is for the angle 1.00
The tangent value for this angle is 1.56
4.2 What is the output of the following program? Explain.
#include
void f(int i, int j) {
i = 5;
j = j + i;
cout << "f: i = " << i << endl;
cout << "f: j = " << j << endl;
}
int main () {
int i = 15;
int j = 30;
f(i, j);
cout << "main: i = " << i << endl;
cout << "main: j = " << j << endl;
}
The output for this program is:
f: i = 5
f: j = 35
main: i = 15
main: j = 30
This is the output because the value initialized for i was reinitialized to 5 in the function, instead of using the passed value of 15. So when the function f printed the values, i and j were 5 and 30. Then when the main function printed the values of i and j, they were 15 and 30 as they were initialized in main. There is also no return value to come back from the function since it has a void return type, so the new values of i and j were not passed back to the main function.
A Dialogue on Code Segments
STUDENT: I notice the next question indicates I should “write a function” instead of “write a
program.” Does that mean I don’t have to write a full program?
INSTRUCTOR: You should write a simple program to test your code. All you need in this case is a
main function that calls your function with appropriate arguments. You will turn in a complete
program, but you will only be graded on the code specifically mentioned in the question.
4.3 Write a float function GetRadius() that prompts the user for a radius, extracts the user’s
response, and then returns the response as its value.
// -------------------------------------------------------------
// Program CS110ques4_3
//
// Purpose: Reads a floating point radius of a circle from a
// function and displays the value after being passed
// back to the main function.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
#include
using std::setprecision;
using std::fixed;
void showPurpose();
float GetRadius();
void showResults(float a);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for the radius of a circle\n";
cout << "and print it out. This program uses a function to\n";
cout << "obtain the radius.\n\n";
}
float GetRadius()
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: A float radius is returned.
// ------------------------------------------------------------
{
float r;
cout << "Enter a radius as a floating point: "; // prompt
cin >> r; // read a float
return r;
}
void showResults(float a)
// -----------------------------------------------------------
// Preconditions : a is set to the radius.
// Postconditions: Displays the radius.
// -----------------------------------------------------------
{
cout << setprecision(2) << fixed;
cout << "\nThe radius is " << a << endl;
}
// function main begins program execution
int main()
{
float radius; // radius to be input by user
showPurpose();
radius = GetRadius();
showResults(radius);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for the radius of a circle
and print it out. This program uses a function to
obtain the radius.
Enter a radius as a floating point: 5.9
The radius is 5.90
4.4 Create an enumerated type for the days of the week. Write a program that prompts the user
for a day of the week, indicated by a number (1 for Sunday, 2 for Monday, etc.) and then
displays whether that day is a weekday or weekend. Make use of a switch statement and
your enumerated type.
// -------------------------------------------------------------
// Program CS110ques4_4
//
// Purpose: Reads an integer representing a day of the week.
// Then prints out the day as a word and shows if it
// is a weekend or a weekday.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
void showPurpose();
int getDay();
void determineWeekend(int a);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for a day of the week as a\n";
cout << "number and print it out, as well as stating if it\n";
cout << "is a weekend or a weekday.\n\n";
}
int getDay()
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: An integer representing a day of the week.
// ------------------------------------------------------------
{
int d;
// prompt
cout << "Enter a day of the week using and integer:\n";
cout << "Example: 1 = Sunday, 2 = Monday, 3 = Tuesday, etc...\n";
cin >> d; // read an int
return d;
}
void determineWeekend(int a)
// -----------------------------------------------------------
// Preconditions : a is set to the integer representing a
// day of the week.
// Postconditions: Determines if the day is a weekend or a
// weekday and prints the result.
// -----------------------------------------------------------
{
enum Days { Sunday = 1, Monday, Tuesday, Wednesday, Thursday,
Friday, Saturday };
Days dayOfWeek;
switch(a)
{
case 1:
dayOfWeek = Sunday;
break;
case 2:
dayOfWeek = Monday;
break;
case 3:
dayOfWeek = Tuesday;
break;
case 4:
dayOfWeek = Wednesday;
break;
case 5:
dayOfWeek = Thursday;
break;
case 6:
dayOfWeek = Friday;
break;
case 7:
dayOfWeek = Saturday;
break;
default:
cout << "\nInvalid entry." << endl;
return;
break;
}
if(dayOfWeek == Sunday || dayOfWeek == Saturday)
{
cout << "\nYou picked a weekend." << endl;
}
else
{
cout << "\nYou picked a weekday." << endl;
}
}
// function main begins program execution
int main()
{
int day; // day to be input by user
showPurpose();
day = getDay();
determineWeekend(day);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for a day of the week as a
number and print it out, as well as stating if it
is a weekend or a weekday.
Enter a day of the week using and (an?) integer:
Example: 1 = Sunday, 2 = Monday, 3 = Tuesday, etc...
4
You picked a weekday.
-----------------------
This program will ask for a day of the week as a
number and print it out, as well as stating if it
is a weekend or a weekday.
Enter a day of the week using and integer:
Example: 1 = Sunday, 2 = Monday, 3 = Tuesday, etc...
7
You picked a weekend.
-----------------------
This program will ask for a day of the week as a
number and print it out, as well as stating if it
is a weekend or a weekday.
Enter a day of the week using and integer:
Example: 1 = Sunday, 2 = Monday, 3 = Tuesday, etc...
9
Invalid entry.
4.5 Write a function for the following formula. Briefly discuss your choice of parameters and
their types.
Distance: computes the distance d traveled in t seconds by an object that started at rest and
then accelerated at a meters per second per second.
d = at2/2
// -------------------------------------------------------------
// Program CS110ques4_5
//
// Purpose: Reads the acceleration per meter per second per
// second and the time in seconds to compute the
// distance traveled when the object starts stationary.
// Then prints out the distance traveled in that time.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
using std::fixed;
#include
using std::setprecision;
void showPurpose();
void getAccelTime(double &a, double &t);
double calculateDistance(double a, double t);
void showResults(double d, double a, double t);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for the acceleration of a\n";
cout << "stationary object over a period of time in seconds\n";
cout << "in order to compute the distance traveled in that ";
cout << "time.\n\n";
}
void getAccelTime(double &a, double &t)
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: A double for acceleration and a double
// for time in seconds passed by reference.
// ------------------------------------------------------------
{
// prompt
cout << "Enter an acceleration in meters per second per second:\n";
cin >> a; // read a double
// prompt
cout << "Enter a time in seconds for the object to move:\n";
cin >> t; // read a double
}
double calculateDistance(double a, double t)
// ------------------------------------------------------------
// Precondition : a is set to acceleration
// t is set to time in seconds.
// Postcondition: Distance is returned.
// ------------------------------------------------------------
{
double d;
d = .5 * a * t * t;
return d;
}
void showResults(double d, double a, double t)
// -----------------------------------------------------------
// Preconditions : d is set to distance
// a is set to acceleration
// t is set to time in seconds.
// Postconditions: Displays the distance traveled in time t
// given accelleration a.
// -----------------------------------------------------------
{
cout << setprecision(2) << fixed;
cout << "\nThe distance traveled based on acceleration\n";
cout << "of " << a << " over the time ";
cout << t << " is " << d << " meters." << endl;
}
// function main begins program execution
int main()
{
double acceleration = 0; // acceleration to be input by user
double timeSec = 0; // time in seconeds to be input by user
double distance = 0; // variable where distance will be stored
showPurpose();
getAccelTime(acceleration, timeSec);
distance = calculateDistance(acceleration, timeSec);
showResults(distance, acceleration, timeSec);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for the acceleration of a
stationary object over a period of time in seconds
in order to compute the distance traveled in that time.
Enter an acceleration in meters per second per second:
5
Enter a time in seconds for the object to move:
10
The distance traveled based on acceleration
of 5.00 over the time 10.00 is 250.00 meters.
Briefly discuss your choice of parameters and their types.
I chose to pass the acceleration and time by reference when obtaining the input values. This made it easier to get more than one input value with a single function. I chose to pass those same variables by value when calculating the distance because it seemed easier to do the calculations that way and less of a chance to accidentally change their values during the calculation function.
-1
4.6 Write a program that reads in an integer from the keyboard and displays its value doubled. The
reading and displaying should each be separate int functions.
// -------------------------------------------------------------
// Program CS110ques4_6
//
// Purpose: Reads an integer from the user and displays its
// double using seperate functions.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
void showPurpose();
int getInteger();
void displayDouble(int a);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for an integer and then \n";
cout << "dsiplays its double\n\n";
}
int getInteger()
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: An integer is returned.
// ------------------------------------------------------------
{
int i;
cout << "Enter an integer: "; // prompt
cin >> i; // read an integer
return i;
}
void displayDouble(int a)
// -----------------------------------------------------------
// Preconditions : a is set to the integer to be doubled.
// Postconditions: Displays the number and its double.
// -----------------------------------------------------------
{
cout << "\n" << a << " doubled is " << a * a << endl; }
//You were asked to display the value doubled. By using a * a, you are displaying the square of a, not double a, which is 2 * a.
// function main begins program execution
int main()
{
int number; // an integer to be input by user
showPurpose();
number = getInteger();
displayDouble(number);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for an integer and then
dsiplays its double
Enter an integer: 12
12 doubled is 144 //No. 144 is 12 squared. 12 doubled is 2 * 12 or 24.
Sample, correctly-coded answer to this question:
#include
int read (int);
int display (int);
int main () {
int number = -1;
number = read (number);
display (number);
return 0;
}
int read (int userNum) {
cout << “ Enter an integer and I will show you the double. ”;
cin >> usereNum;
return userNum;
}
int display (int num2double) {
cout << “The number doubled is “ << num2double*2 << ”.” << endl;
return 0;
}
5.1 How does the use of inline speed up the execution of a program? What is the disadvantage
of using inline?
How does the use of inline speed up the execution of a program? By using inline, a function that is written separately is actually included in the main function when it is compiled. The speeds up execution because main no longer needs to call a separate function.
What is the disadvantage of using inline? The disadvantage of using inline is that the actual file size is larger than it would have been if inline had not been used.
5.2 What is the output produced by the following program? Explain.
#include
void testfunc(int x, int y = 10) {
cout << x + y;
}
int main () {
testfunc(3);
return 0;
}
What is the output produced by the following program?
The output of this program, once an include, using statement and a prototype were added is 13
Explain. 13 was the output, because 3 was passed as a parameter, and y had already been initialized to 10 in the function definition. So the passed x value and the initialized y value were added together to be 13.
5.3 What is the output of the following program? Explain.
#include
void f(int i, int &j) {
i = 5;
j = j + i;
cout << "f: i = " << i << endl;
cout << "f: j = " << j << endl;
}
int main () {
int i = 15;
int j = 30;
f(i, j);
cout << "main: i = " << i << endl;
cout << "main: j = " << j << endl;
}
What is the output of the following program?
f: i = 5
f: j = 35
main: i = 15
main: j = 35
Explain. The first i value printed is from I being initialized to 5 in the function f. The first j value is from using the initialized value of i and the referenced value of j (30) to be added to 35. The second value of i printed is based on the initialized value of 15 in the main function (outside of the function). This was overridden while in the function, but now that the control of the program is outside of the function, the value of 15 as initialized in main is used. The second value of j printed is the new value of j. This change happened in the function because the function was using a reference to the memory location of the j variable, so when the addition and passing of value to j happened inside the function f, the referenced memory location for j was updated to 35. That is why 35 prints when j is printed in the main function.
5.4 Write a program that reads in two integers from the keyboard and displays their sum. The
reading function should read in both integers at the same time. Both the reading and
displaying functions should be separate void functions.
// -------------------------------------------------------------
// Program CS110ques5_4
//
// Purpose: Reads two integers from the user and displays their
// sum, using two separate functions to get and print.
//
// Author : Janine Bouyssounouse
// Date : July 19, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
void showPurpose();
void getIntegers(int &integer1, int &integer2);
void displaySum(int &integer1, int &integer2);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for two integers and then \n";
cout << "dsiplay their sum.\n\n";
}
void getIntegers(int &integer1, int &integer2)
// ------------------------------------------------------------
// Precondition : none.
// Postcondition: Two integers are referenced.
// ------------------------------------------------------------
{
cout << "Enter two integers separated by a space: "; // prompt
cin >> integer1 >> integer2; // read integers
}
void displaySum(int &integer1, int &integer2)
// -----------------------------------------------------------
// Preconditions : Referenced variables are used.
// Postconditions: Displays the sum of the referenced variables.
// -----------------------------------------------------------
{
cout << "\nThe sum of " << integer1 << " and ";
cout << integer2 << " is " << integer1 + integer2 << endl;
}
// function main begins program execution
int main()
{
int integer1 = 0; // an integer to be input by user
int integer2 = 0; // an integer to be input by user
showPurpose();
getIntegers(integer1, integer2);
displaySum(integer1, integer2);
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for two integers and then
dsiplay their sum.
Enter two integers separated by a space: 3 12
The sum of 3 and 12 is 15
5.5 What is the output of the following program? Explain.
#include
float someNum = 3.0;
int main () {
int someNum = 2;
cout << someNum << endl;
cout << ::someNum << endl;
return 0;
}
What is the output of the following program?
2
3
Explain. The :: symbol is a unary scope operator. It is used when a local and global variable have the same name. Using it in front of a variable name specifies using the global variable. The line: cout << someNum << endl; is using the local variable declared and initialized in the main function as 2. The line: cout << ::someNum << endl; is using the global variable declared and initialized outside of the main function as 3.0.
5.6 When two or more functions have the same name, how does the compiler determine which one to use for a particular function call? Functions with the same name in the same program are defined with different parameter types. This is called overloading a function. The function call uses the function that matches the type in its parameter.
5.7 Write a void function called swap that takes two integer parameters and swaps their contents. Write another swap function that takes two double arguments. Write a short main function that calls both swap functions and demonstrates that the contents have been swapped. Cout statements should appear in function main.
// -------------------------------------------------------------
// Program CS110ques5_7
//
// Purpose: Reads two integers and two doubles and then seaps
// their values and prints out the results.
//
// Author : Janine Bouyssounouse
// Date : July 20, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
void showPurpose();
void swap(int &a, int &b);
void swap(double &x, double &y);
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for two integers and two\n";
cout << "doubles. Then the values will be swapped. The\n";
cout << "results are then displayed.\n\n";
}
void swap(int &a, int &b)
// ------------------------------------------------------------
// Precondition : a is set to the first int
// b is set to the second int.
// Postcondition: Values are swapped and returned by reference.
// ------------------------------------------------------------
{
int c;
c = a;
a = b;
b = c;
}
void swap(double &x, double &y)
// ------------------------------------------------------------
// Precondition : x is set to the first double
// y is set to the second double.
// Postcondition: Values are swapped and returned by reference.
// ------------------------------------------------------------
{
double z;
z = x;
x = y;
y = z;
}
// function main begins program execution
int main()
{
int a = 0; // first integer to be input by user
int b = 0; // second integer to be input by user
double x = 0; // first double to be input by user
double y = 0; // second double to be input by user
showPurpose();
// prompt
cout << "Enter the first integer:\n";
cin >> a; // read an int
// prompt
cout << "Enter the second integer:\n";
cin >> b; // read an int
// prompt
cout << "\nEnter the first double:\n";
cin >> x; // read a double
// prompt
cout << "Enter the second double:\n";
cin >> y; // read a double
swap(a, b);
swap(x, y);
cout << "\n\nThe values are now swapped.\n\n";
cout << "The first integer is now " << a << endl;
cout << "The second integer is now " << b << endl << endl;
cout << "The first double is now " << x << endl;
cout << "The second double is now " << y << endl;
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for two integers and two
doubles. Then the values will be swapped. The
results are then displayed.
Enter the first integer:
5
Enter the second integer:
17
Enter the first double:
3.4
Enter the second double:
8.1
The values are now swapped.
The first integer is now 17
The second integer is now 5
The first double is now 8.1
The second double is now 3.4
5.8 Rewrite your answer for the previous question, using a single swap template instead of two
swap functions.
// -------------------------------------------------------------
// Program CS110ques5_8
//
// Purpose: Reads two integers and two doubles and then swaps
// their values using only one swap function and
// prints out the results.
//
// Author : Janine Bouyssounouse
// Date : July 20, 2004
// -------------------------------------------------------------
#include
using std::cout;
using std::cin;
using std::endl;
template < class T >
void swap(T &m, T &n);
void showPurpose();
void showPurpose()
// -------------------------------------------------------------
// Preconditions : none.
// Postconditions: The purpose of this program has been written
// to standard output.
// -------------------------------------------------------------
{
cout << "This program will ask for two integers and two\n";
cout << "doubles. Then the values will be swapped. The swaps\n";
cout << "are done in one function. The results are then displayed.\n\n";
}
template < class T >
void swap(T &m, T &n)
// ------------------------------------------------------------
// Precondition : m is set to the first value
// n is set to the second value.
// Postcondition: Values are swapped and returned by reference.
// ------------------------------------------------------------
{
T z = m;
m = n;
n = z;
}
// function main begins program execution
int main()
{
int a = 0; // first integer to be input by user
int b = 0; // second integer to be input by user
double x = 0; // first double to be input by user
double y = 0; // second double to be input by user
showPurpose();
// prompt
cout << "Enter the first integer:\n";
cin >> a; // read an int
// prompt
cout << "Enter the second integer:\n";
cin >> b; // read an int
// prompt
cout << "\nEnter the first double:\n";
cin >> x; // read a double
// prompt
cout << "Enter the second double:\n";
cin >> y; // read a double
swap(a, b);
swap(x, y);
cout << "\n\nThe values are now swapped.\n\n";
cout << "The first integer is now " << a << endl;
cout << "The second integer is now " << b << endl << endl;
cout << "The first double is now " << x << endl;
cout << "The second double is now " << y << endl;
return 0; // indicate that program ended successfully
} // end function main
output:
This program will ask for two integers and two
doubles. Then the values will be swapped. The swaps
are done in one function. The results are then displayed.
Enter the first integer:
2
Enter the second integer:
87
Enter the first double:
3.54
Enter the second double:
56.15
The values are now swapped.
The first integer is now 87
The second integer is now 2
The first double is now 56.15
The second double is now 3.54
6.1 Why do we have both debug and release builds?
Debugging fixes the bugs in a program. Releasing a build allows it to be publicly distributed so that others can run the program. This is only done after the debugging process has been completed.
6.2 What is the difference between step over, step into, step out, and run to cursor?
Step over – This executes a single line of the program, including any functions called by that line of code.
Step into – This executes a single line of code by going into the functions called by that line of code.
Step out – This brings the debugger out of the current function being executed after completing the current function.
Run to cursor – This sets a temporary break point on the line of code where the insertion point is.
6.3 Find and describe the errors in the following program. Use the debugger. Note: it’s
important to type this program in carefully; otherwise you may introduce new errors and/or
remove the existing ones without intending to.
//this program computes how much money will
//accumulate after so many years of investing
#include
float Balance = 0.0;
float Interest;
float YearlyCont;
int NumYears;
//this function computes one year of investment
float newBalance(float balance);
int main () {
cout << "How much money will you deposit"
<< "each year?" << endl;
cin >> YearlyCont;
cout << "What interest rate will you get"
<<"(enter 5% as .05)?" << endl;
cin >> Interest;
cout << "How many years will you invest?"
<< endl;
cin >> NumYears;
for(int i = 1; i <= NumYears; i++);
Balance = newBalance(Balance);
cout << "Money at end of investment: "
<< Balance << endl;
return 0;
}
float newBalance(float balance) {
//add in this year’s deposit
balance = balance + YearlyCont;
//add in this year’s interest
//Note: the f in 1.0f is explained in section
//18.8, chapter 18
balance = (Interest + 1.0f) * Balance;
return balance;
}
There shouldn’t be a semicolon at the end of the for statement. That just increments i and does not execute the balance function for each year, so the calculation is incorrect.
Both balance and Balance were being used in the function newBalance. Since only one of them was being passed, this had to be changed. They were considered different variables, since variables are case sensitive. I changed Balance to balance to make it consistent with the rest of the function.
//this program computes how much money will
//accumulate after so many years of investing
#include
float Balance = 0.0;
float Interest;
float YearlyCont;
int NumYears;
//this function computes one year of investment
float newBalance(float balance);
int main ()
{
cout << "How much money will you deposit"
<< "each year?" << endl;
cin >> YearlyCont;
cout << "What interest rate will you get"
<<"(enter 5% as .05)?" << endl;
cin >> Interest;
cout << "How many years will you invest?"
<< endl;
cin >> NumYears;
for(int i = 1; i <= NumYears; i++) //no more semicolon
Balance = newBalance(Balance);
cout << "Money at end of investment: "
<< Balance << endl;
return 0;
}
float newBalance(float balance)
{
//add in this year's deposit
balance = balance + YearlyCont;
//add in this year's interest
//Note: the f in 1.0f is explained in section
//18.8, chapter 18
balance = (Interest + 1.0f) * balance; //changed Balance to balance
return balance;
}
output:
How much money will you depositeach year?
100
What interest rate will you get(enter 5% as .05)?
.1
How many years will you invest?
5
Money at end of investment: 671.561
6.4 Here’s a more subtle problem. Run this program and see what the problem is. Now step
through the program. Does the problem disappear? What is happening?
#include
#include
#include
int main () {
int value;
int count = 0;
for (int i = 1; i <= 10; i++) {
srand(time(0));
value = rand() % 2;
if (value == 0)
count++;
}
cout << "Out of 10 trials, heads came up"
<< count << " times." << endl;
return 0;
}
Answer to 6.4 – When I ran through the program the first time, I ended up with ten as the number of heads. I knew this couldn’t be correct, since it should be closer to half or five. I ran it through the compiler and I didn’t see a problem. The only thing I can see is that the random seed is inside the for loop and it is using the computer’s time in seconds to reseed the random function every time through the loop. If the program runs through the loops in less than a second, then the random function would be fed the same seed each time, since the clock is on the same second each time. My resolution to this would be to put the srand line of code outside of the loop, then the random function would be fed one seed per running of the program and it would move forward from there. This would make each time though the program unique, while still trying to preserve the “randomness” of each run through of the program.
website created by Janine Bouyssounouse.
Last updated 02/08/07