Академический Документы
Профессиональный Документы
Культура Документы
Write a program that repeatedly asks the user to enter pairs of numbers until at least one
of the pair is 0. For each pair, the program should use a function to calculate the harmonic
mean of the numbers. The function should return the answer to main(), which
should report the result. The harmonic mean of the numbers is the inverse of the average
of the inverses and can be calculated as follows:
harmonic mean = 2.0 x y / (x + y)
My Answer:
#include <iostream>
int main()
{
cout << "The harmonic mean of " << x << " and " << y << " is " << mean(x,y);
cout << "\n\nNext pair of numbers (0 to stop): ";
}
return meanV;
}
1.
Freddy says:
October 26, 2011 at 9:45 am
For line 10 it says that the identifier cout is unidentified & for line 13, it says that
identifier cin is unidentified
Reply
Daniel says:
March 27, 2013 at 3:11 pm
using namespace std; & iostream??
2. Write a program that asks the user to enter up to 10 golf scores, which are to be stored
in an array. You should provide a means for the user to terminate input prior to entering
10 scores. The program should display all the scores on one line and report the average
score. Handle input, display, and the average calculation with three separate arrayprocessing
functions.
My Answer:
1 #include <iostream>
2
3 const int mysize = 10;
if (failflag != 0)
32
33
34
35
36
if (ar[i] == -1)
37
failflag = 0;
38 }
39}
40
41void displayinput (int *ar, int arsize)
42{
43 std::cout << "\nDisplaying input on one line: ";
44 for (int i=0; i < arsize && (ar[i] != -1); i++)
45
46}
47
48double average (const int *ar, int arsize)
49{
50 double avg = 0;
51 double total = 0;
52 int elements = 0;
53
54 for (int i=0; i < arsize && (ar[i] != -1); i++)
55 {
56
57
elements++;
58 }
59
60 std::cout << "\nTotal = " << total;
61 std::cout << "\nElements = " << elements;
62 avg = total / elements;
63 return avg;
64}
1.
Saad says:
January 31, 2012 at 12:45 pm
// C++ Primer Plus Exercise
// Chapter 7, Exercise 2
#include
//- Function Prototyping
void input(int []);
double average(int[]);
void display(int[]);
//
int main()
{
using namespace std;
int scores[10]={};
input(scores);
display(scores);
if(average(scores))
cout << "\n Average score: " << average(scores);
return 0;
}
//- Function(s)
//+ Input
void input(int scores[])
{
int buffer = 0;
std::cout << "Please enter scores, maximum of 10 (-ve number to quit)\n";
for(int i=0; i<10; i++)
{
std::cout << "#" << i+1 <> buffer)
{
if(buffer<0)
{
std::cout << "Terminating due to -ve input, " << i << " score(s) read\n";
break;
}
else
scores[i] = buffer;
}
else
{
std::cout << "\nInvalid input, terminating";
std::cin.clear();
std::cin.get();
break;
}
}
}
//++
//+ Average
double average(int scores[])
{
double total = 0;
int counter = 0;
for(int i=0; i<10; i++)
{
if(scores[i]=='' && i==0)
{
std::cout << "\nThe score card appears to be empty, no average to report.";
return 0;
}
else if(scores[i] != '')
{
total += scores[i];
counter++;
}
}
return (total/counter);
}
//++
//+ Display
void display(int scores[])
{
for(int i=0; i<10; i++)
{
if(scores[i]=='' || i==10)
{
if(i == 0)
{
std::cout << "\nScore card appears to be empty exiting";
break;
}
else
{
std::cout << "\nEnd of score card reached at entry #" << i;
break;
}
}
std::cout << "#" << i+1 << ": " << scores[i] << "\t";
}
}
//++
//
44{
45 Mystruct->volume = Mystruct->height*Mystruct->width*Mystruct->length;
46}
4. Many state lotteries use a variation of the simple lottery portrayed by Listing 7.4. In
these variations you choose several numbers from one set and call them the field numbers.
For example, you might select 5 numbers from the field of 147). You also pick a
single number (called a mega number or a power ball, etc.) from a second range, such as
127. To win the grand prize, you have to guess all the picks correctly. The chance of
winning is the product of the probability of picking all the field numbers times the probability
of picking the mega number. For instance, the probability of winning the example
described here is the product of the probability of picking 5 out of 47 correctly times the
probability of picking 1 out of 27 correctly. Modify Listing 7.4 to calculate the probability
of winning this kind of lottery.
My Answer:
1 #include <iostream>
2
3 long double probability(unsigned numbers, unsigned picks);
4 double lotterychance(int, int, int, int, long double (*pb)(unsigned, unsigned));
5
6 int main()
7 {
8 using namespace std;
9
10cout << "The lottery chance of winning state lottery is ";
11cout << lotterychance(47,5,27,1,probability);
12
13cout << "bye\n";
14cin.get();
15cin.get();
16return 0;
17}
18// the following function calculates the probability of picking picks
19// numbers correctly from numbers choices
chance = pb(field,fieldselect)*pb(meganum,megaselect);
36
37
}
return chance;
5. Define a recursive function that takes an integer argument and returns the factorial of
that argument. Recall that 3 factorial, written 3!, equals 3 2!, and so on, with 0!
defined as 1. In general, if n is greater than zero, n! = n * (n 1)!. Test your function in a
program that uses a loop to allow the user to enter various values for which the program
reports the factorial.
My Answers:
1 #include <iostream>
2
3 int factorial (int);
4
5 int main()
6 {
31 }
32
33 return factor;
34}
1.
Fran says:
July 27, 2012 at 10:21 am
Define a recursive function
Your function doesnt call itself.
I did something like this:
int Factorial(int res, int n, int c)
{
while (c < n)
{
c++;
res *= c;
Factorial(res, n, c);
}
return res;
}
Reply
2.
Daniel says:
March 27, 2013 at 5:16 pm
i think we can use a better way to realize the factorial by using the tail recursion:
int factorial (int number,int acc)
// acc is an accumulator to record the each computing n*(n-1)
// so acc shall be initialized as 1
{
if (number==0) return acc;
return factorial(number-1,number*acc);
}
array size and reverses the order of the values stored in the array.
The program should use these functions to fill an array, show the array, reverse the array,
show the array, reverse all but the first and last elements of the array, and then show the
array.
My Answers:
1 #include <iostream>
2
3 const int mysize = 7;
4 int Fill_array (double [], int);
5 void Show_array (double [], int);
6 void Reverse_array (double [], int, bool);
7
8 int main()
9 {
10using namespace std;
11
12double ar[mysize];
13int actualsize = 0;
14
15actualsize = Fill_array(ar,mysize);
16Show_array(ar,actualsize);
17Reverse_array(ar,actualsize,false);
18Show_array(ar,actualsize);
19Reverse_array(ar,actualsize,true);
20Show_array(ar,actualsize);
21
22cin.get();
23cin.get();
24return 0;
25}
26
27int Fill_array (double ar[], int arsize)
28{
29 using namespace std;
30 int entries = 0;
31 double temp;
32 bool endflag = false;
33 cout << "\nFilling Array: " << endl;
34
35 for (int i=0; i < arsize && endflag == false; i++)
36 {
37
38
39
40
ar[i]=0;
41
cin.clear();
42
cin.get();
43
cin.get();
44
45
endflag = true;
46
47
48
else
49
50
ar[i] = temp;
51
entries++;
52
53 }
54
55 return entries;
56}
57
58void Show_array (double ar[], int arsize)
59{
60 std::cout << "\nShowing Array: " << std::endl;
61 for (int i=0; i < arsize; i++)
62
std::cout << "Element #" << i+1 << ": " << ar[i] << std::endl;
63}
64
65void Reverse_array (double ar[], int arsize, bool firstlast)
66{
67 double * temp = new double [arsize];
68
69 for (int i=0; i < arsize; i++)
70
temp[i] = ar[i];
71
72 for (int j=0; j < arsize; j++)
73 {
74
75
continue;
76
else
77
ar[j] = temp[arsize-(j+1)];
78 }
79
80 delete [] temp;
81
82 std::cout << "\nArray Reverse is done.\n";
83}
1.
Saad says:
February 6, 2012 at 8:43 pm
return i;
}
void showArray(double array[], int size)
{
for(int i=0; i<size; i++)
{
std::cout << "Item #"<< i+1 << " " << array[i] << "\n";
}
}
void reverseArray(double array[], int size)
{
double temp;// = array[size-1];
for(int i=0, j=size-1; i<j; i++, j)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
//
Reply
2.
<div class="le-cah-container">
<div class="le-cah-titleblock">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol start="1" style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#008000">// Ch. 7.6 ReverseArray and ReverseArray
except the first and last value using the same function</span></li>
<li style="background: #f3f3f3"> </li>
<li><span style="color:#0000ff">#include</span> <span
style="color:#a31515">"stdafx.h"</span></li>
<li style="background: #f3f3f3"><span style="color:#0000ff">#include</span>
<span style="color:#a31515"><iostream></span></li>
<li><span style="color:#0000ff">using</span> <span
style="color:#0000ff">namespace</span> std;</li>
cin>>a[i]; i++);</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">return</span>
i;</li>
<li>}</li>
<li style="background: #f3f3f3"> </li>
<li><span style="color:#0000ff">void</span> showArray(<span
style="color:#0000ff">double</span> *a, <span style="color:#0000ff">int</span>
size)</li>
<li style="background: #f3f3f3">{</li>
<li> <span style="color:#0000ff">for</span> (<span
style="color:#0000ff">int</span> i=0; i<size; i++)</li>
<li style="background: #f3f3f3">
cout<<a[i]<<<span
style="color:#a31515">' '</span>;</li>
<li> cout<<endl;</li>
<li style="background: #f3f3f3">}</li>
<li> </li>
<li style="background: #f3f3f3"><span style="color:#0000ff">void</span>
reverseArray(<span style="color:#0000ff">double</span> *a, <span
style="color:#0000ff">int</span> size)</li>
<li>{</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">double</span>
hold;</li>
<li> <span style="color:#0000ff">int</span> i, j;</li>
<li style="background: #f3f3f3"> <span style="color:#0000ff">for</span> (i=0,
j=size-1; i<j; i++, j)</li>
<li> {</li>
<li style="background: #f3f3f3">
hold=a[i];</li>
<li>
a[i]=a[j];</li>
<li style="background: #f3f3f3">
a[j]=hold;</li>
<li> }</li>
<li style="background: #f3f3f3">}</li>
</ol>
</div>
</div>
Reply
3.
#include <iostream>
using namespace std;
int fillArray(double *a, int size);
void showArray(double *a, int size);
void reverseArray(double *a, int size);
int _tmain(int argc, _TCHAR* argv[])
{
int size=10;
double a[10];
cout<<"Please enter up to 10 numbers to fill an array. Enter non-numeric input to
stop: \n";
size=fillArray(a, size);
cout<<"Here's your array: \n";
showArray(a, size);
cout<<"Here's your array reversed: \n";
reverseArray(a, size);
showArray(a, size);
reverseArray(a, size);
cout<<"Here's your array with all but the first and last numbers reversed: \n";
reverseArray(a+1, size-2); // a+1 moves the start of the array to the 1st element,
size-2 moves the end of the array to the second to last element (-2 since a was
moved +1)
showArray(a, size);
return 0;
}
int fillArray(double *a, int size)
{
int i;
for (i=0; i<size && cin>>a[i]; i++);
return i;
}
void showArray(double *a, int size)
{
for (int i=0; i<size; i++)
cout<<a[i]<<' ';
cout<<endl;
}
void reverseArray(double *a, int size)
{
double hold;
int i, j;
for (i=0, j=size-1; i<j; i++, j)
{
hold=a[i];
a[i]=a[j];
a[j]=hold;
}
}
Reply
4.
7. Redo Listing 7.7, modifying the three array-handling functions to each use two pointer
parameters to represent a range. The fill_array() function, instead of returning the
actual number of items read, should return a pointer to the location after the last location
filled; the other functions can use this pointer as the second argument to identify
the end of the data.
1 #include <iostream>
2 const int Max = 5;
3
4 double * fill_array(double * begin, double * end);
5 void show_array(const double * begin, const double * end);
6 void revalue(double factor, double * begin, double * end);
7
8 int main()
9 {
10using namespace std;
11double properties[Max];
12double * size = fill_array(properties, properties + Max);
13
14show_array(properties, size);
15cout << "Enter revaluation factor: ";
16
17double factor;
18cin >> factor;
19
20revalue(factor, properties, size);
21show_array(properties, size);
22
23
24cout << "Done.\n";
25cin.get();
26cin.get();
27return 0;
28}
29
30double * fill_array(double * begin, double * end)
31{
32 using namespace std;
33 double temp;
34 int i=0;
35 for (begin; begin < end; begin++)
36 {
37
38
cin.clear();
continue;
break;
49 * begin = temp;
50 i++;
51 }
52 return begin;
53}
54
55// the following function can use, but not alter,
56// the array whose address is ar
57void show_array(const double * begin, const double * end)
58{
59 using namespace std;
60 int i = 0;
61 for (begin; begin < end; begin++)
62 {
63
64
65
i++;
66 }
67}
68
69// multiplies each element of ar[] by r
70void revalue(double factor, double * begin, double * end)
71{
72 for (begin; begin < end; begin++)
73 * begin *= factor;
74}
8. This exercise provides practice in writing functions dealing with arrays and structures.
The following is a program skeleton. Complete it by providing the described functions:
#include
using namespace std;
const int SLEN = 30;
struct student {
char fullname[SLEN];
char hobby[SLEN];
int ooplevel;
};
// getinfo() has two arguments: a pointer to the first element of
// an array of student structures and an int representing the
// number of elements of the array. The function solicits and
// stores data about students. It terminates input upon filling
// the array or upon encountering a blank line for the student
// name. The function returns the actual number of array elements
// filled.
int getinfo(student pa[], int n);
// display1() takes a student structure as an argument
// and displays its contents
void display1(student st);
// display2() takes the address of student structure as an
// argument and displays the structures contents
void display2(const student * ps);
// display3() takes the address of the first element of an array
// of student structures and the number of array elements as
// arguments and displays the contents of the structures
void display3(const student pa[], int n);
int main()
{
cout << Enter class size: ;
int class_size;
cin >> class_size;
while (cin.get() != \n)
continue;
student * ptr_stu = new student[class_size];
int entered = getinfo(ptr_stu, class_size);
for (int i = 0; i < entered; i++)
{
display1(ptr_stu[i]);
display2(&ptr_stu[i]);
}
display3(ptr_stu, entered);
delete [] ptr_stu;
cout << Done\n;
return 0;
}
My Answer:
1
#include <iostream>
2
3
4
5
6
7
struct student {
char fullname[SLEN];
char hobby[SLEN];
10 int ooplevel;
11 };
12
13 // getinfo() has two arguments: a pointer to the first element of
14 // an array of student structures and an int representing the
15 // number of elements of the array. The function solicits and
16 // stores data about students. It terminates input upon filling
17 // the array or upon encountering a blank line for the student
18 // name. The function returns the actual number of array elements
19 // filled.
20 int getinfo(student pa[], int n);
21 // display1() takes a student structure as an argument
22 // and displays its contents
23 void display1(student st);
24 // display2() takes the address of student structure as an
25 // argument and displays the structures contents
26 void display2(const student * ps);
27 // display3() takes the address of the first element of an array
28 // of student structures and the number of array elements as
continue;
41
42 student * ptr_stu = new student[class_size];
43 int entered = getinfo(ptr_stu, class_size);
44 for (int i = 0; i < entered; i++)
45 {
46
display1(ptr_stu[i]);
47
display2(&ptr_stu[i]);
48 }
49
50 display3(ptr_stu, entered);
51
52 delete [] ptr_stu;
53 cout << "\nDone";
54
55 cin.get();
56 cin.get();
57 return 0;
58 }
59
int i;
63
64
65
66
67
cin.getline(pa[i].fullname,SLEN);
68
if (pa[i].fullname[0] == '\0')
69
70
71
break;
72
73
74
cin.getline(pa[i].hobby,SLEN);
75
76
77
78
return i;
79 }
80
81 void display1(student st)
82 {
83
84
85
86
87
88 }
89
90 void display2(const student * ps)
91 {
92
93
94
95
96
97
98 }
99
100void display3(const student pa[], int n)
101{
102 if (n == 0)
103
return;
109
110
111
112
113 }
114 cout << "\n\n========= END OF Display3 ========";
115}
Saad says:
February 12, 2012 at 3:11 pm
8. Design a function calculate() that takes two type double values and a pointer to a
function that takes two double arguments and returns a double. The calculate() function
should also be type double, and it should return the value that the pointed-to function
calculates, using the double arguments to calculate(). For example, suppose you
have this definition for the add() function:
double add(double x, double y)
{
return x + y;
}
Then, the function call in
double q = calculate(2.5, 10.4, add);
would cause calculate() to pass the values 2.5 and 10.4 to the add() function and
then return the add() return value (12.9).
Use these functions and at least one additional function in the add() mold in a program.
The program should use a loop that allows the user to enter pairs of numbers. For each
pair, use calculate() to invoke add() and at least one other function. If you are feeling
adventurous, try creating an array of pointers to add()-style functions and use a loop to
successively apply calculate() to a series of functions by using these pointers. Hint:
Heres how to declare such an array of three pointers:
double (*pf[3])(double, double);
You can initialize such an array by using the usual array initialization syntax and function
names as addresses.
My Answer:
1 #include <iostream>
2
3 double shifr1(double x, double y);
4 double shifr2(double x, double y);
5 double shifr3(double x, double y);
6 double calculate (double x, double y, double (*pf[3])(double, double));
7
8 int main()
9 {
10
11using namespace std;
12
13double (*pf[3])(double,double) = {shifr2,shifr1,shifr3};
14int x,y = 0;
15
16cout << "Enter two pairs of numbers (-1) to exit: ";
17
18while (cin >> x >> y)
19{
20 if (x == -1 || y == -1)
21
break;
29}
30
31double shifr1(double x, double y)
32{
33 double shifr = 0;
34
35 shifr = x + y;
36
37 return shifr;
38}
39
40double shifr2(double x, double y)
41{
42 double shifr = 0;
43
44 shifr = x * y;
45
46 return shifr;
47}
48
49double shifr3(double x, double y)
50{
51 double shifr = 0;
52
53 shifr = x - y;
54
55 return shifr;
56}
57
58double calculate (double x, double y, double (*pf[3])(double x2, double y2))
59{
60 double calc = 0;
61
62 for (int i=0; i < 3; i++)
63 {
64
65 }
66
67 return calc;
68}
1.
Saad says:
February 12, 2012 at 7:30 pm
// C++ Primer Plus Exercise
// Chapter 7, Exercise 9
#include
//- Function(s) Prototype(s)
double calculate(double, double, double (*[])(double, double));
double add(double, double);
double subt(double, double);
double mult(double, double);
double div(double, double);
int main()
{
using namespace std;
double (*pfunct[4])(double, double) = {add, subt, mult, div};
// double (*npfunt)(double, double) = new double[4]; TODO:: Figure out how to
create a dynamic array of pointer-to-function
double x, y;
cout <> x >> y)
{
calculate(x, y, pfunct);
cout << "\nPlease enter two numbers to perform calculations on (no numeric to quit):
";
}
cout << "\nAdios!";
return 0;
}
//- Function(s)
double calculate(double x, double y, double (*funct[])(double, double))
{
for(int i=0; i<4; i++)
{
switch (i+1)
{
case 1: std::cout << "\nAdd Function: ";
break;
case 2: std::cout << "\nSubtract Function: ";
break;
case 3: std::cout << "\nMultiply Function: ";
break;
case 4: std::cout << "\nDivide Function: ";
break;
}
std::cout << (*(funct+i))(x,y);
}
return 0;
}
double add(double x, double y)
{
return x+y;
}
double subt(double x, double y)
{
return x-y;
}
double mult(double x, double y)
{
return x*y;
}
double div(double x, double y)
{
return x/y;
}
//