Skip to content

Instantly share code, notes, and snippets.

@fhs
Created October 27, 2011 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fhs/1318463 to your computer and use it in GitHub Desktop.
Save fhs/1318463 to your computer and use it in GitHub Desktop.
Assignment #2 solution
// #1. Ex 5.2 question 9 solution
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int
main(void)
{
int i;
double e, e1, fact;
e = 1; // 1/0!
fact = 1; // 1!
e1 = e+1/fact; // 1/0! + 1/1!
i = 2;
while(fabs(e1-e) >= 10e-9){
e = e1;
fact *= i;
e1 += 1/fact;
i++;
}
cout << "e = " << fixed << setprecision(8) << e1 << endl;
return 0;
}
// #1. Ex 5.2 question 9 solution (optimized)
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int
main(void)
{
int i;
double e, t, fact;
fact = 1;
e = 1;
i = 1;
do {
fact *= i;
t = 1/fact;
e += t;
i++;
} while(t >= 10e-9);
cout << "e = " << fixed << setprecision(8) << e << endl;
return 0;
}
// #2 solution
#include <iostream>
using namespace std;
int
main(void)
{
int x;
do {
cout << "Enter x: ";
cin >> x;
} while (x < 10 || 50 < x);
for(int i = 0; i < x; i++){
for(int j = 0; j < i+1; j++)
cout << "*";
cout << endl;
}
return 0;
}
// #3 solution
#include <iostream>
using namespace std;
int
main(void)
{
int op, left, right, answer, guess, score, nques, again;
bool correct;
double avgscore;
const int ADD = 1, SUB = 2, MUL = 3, DIV = 4;
score = nques = 0;
for(;;){
cout << "[" << ADD << "=add, "
<< SUB << "=subtract, "
<< MUL << "=multiply, "
<< DIV << "=divide]: ";
cin >> op;
if(op != ADD && op != SUB && op != MUL && op != DIV){
cout << "invalid input; try again" << endl;
continue;
}
cout << "Enter the two operands: ";
cin >> left >> right;
if(op == DIV && right == 0){
cout << "cannot divide by zero; try again" << endl;
continue;
}
switch(op){
case ADD:
answer = left + right;
break;
case SUB:
answer = left - right;
break;
case MUL:
answer = left * right;
break;
case DIV:
answer = left / right;
break;
default: // unreachable
cout << "internal error" << endl;
return 2;
}
correct = false;
for(int i = 0; i < 3; i++){
cout << "Enter your answer: ";
cin >> guess;
if(guess == answer){
correct = true;
score++;
break;
}
score--;
}
if(!correct)
cout << "The correct answer is " << answer << endl;
nques++;
cout << "[1=continue, 0=quit]: ";
cin >> again;
if(again == 0)
break;
}
cout << "Number of questions tested: " << nques << endl;
cout << "Your overall score: " << score << endl;
avgscore = score/double(nques);
if(avgscore > 0.5)
cout << "Great" << endl;
else if(avgscore < 0)
cout << "Poor" << endl;
else
cout << "Fine" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment