Solutions to Assignment 3
//3.1
#include
#include
//use namespace std;
int
main(int argc, char **argv) {
long int f0, f1, fk;
int N;
cout << "Enter N and the starting numbers: ";
cin >> N >> f0 >> f1;
if (N < 0) {
cout << "Usage: " << argv[0] << " " << endl;
return -1;
}
switch (N) {
case 0:
fk = f0;
break;
case 1:
fk = f1;
break;
default:
fk = static_cast(pow(2.0, N - 2) * (f0 + f1));
break;
}
cout << "f(" << N << ") is: " << fk << endl;
return 1;
}
//3.2
#include
// use namespace std;
int
main() {
unsigned int id;
cin >> id;
float REG_HRS, wage, overtime, OT_WAGE;
cin >> REG_HRS >> wage >> overtime >> OT_WAGE;
float gross_pay = REG_HRS * wage + overtime*OT_WAGE;
float SOC_SECUR_RATE;
cin >> SOC_SECUR_RATE;
float soc_secur_tax = SOC_SECUR_RATE * gross_pay;
float DEPENDENT_DEDUCTION, dependents;
cin >> DEPENDENT_DEDUCTION >> dependents;
float deductions = DEPENDENT_DEDUCTION * dependents;
float FIT_RATE;
cin >> FIT_RATE;
float fed_inc_tax = FIT_RATE * (gross_pay - deductions);
float UNION_DUES_RATE;
cin >> UNION_DUES_RATE;
float union_dues = UNION_DUES_RATE * gross_pay;
float net_pay = gross_pay - soc_secur_tax - fed_inc_tax - union_dues;
cout << id << ": " << net_pay;
return 1;
}
// 3.3
#include
#include
#include
#include
#include
// use namspace std;
int
main(char argc, char **argv) {
double id, ic = 0.0;
double x, y;
/*
* Without this initialization of the generator mechanism
* the returning sequence every running will be the same
*/
srand(time(NULL));
for (id = 0.0; id < 1000.0; id++) {
x = static_cast(rand() % 10000) / 10000.0;
y = static_cast(rand() % 10000) / 10000.0;
if ((x - .5)*(x - .5) + (y - .5)*(y - .5) <= .25)
ic += 1.0;
}
cout << setprecision(6)
<< "PI/4 = " << ic / id << " and PI = " << 4.0 * ic / id << endl;
return 1;
}
// 3.4
#include
int
main() {
int N, i = 0;
char buffer[30];
cin >> N;
while (N) {
buffer[i++] = N % 2 + '0';
N /= 2;
}
while (i > -1) {
cout << buffer[--i];
}
cout << endl;
return 1;
}
// 3.5
#include
// use namespace std;
int
palindrom(int N) {
char c1, c2;
int r;
if (N < 1)
return 1;
else if (N == 1) {
cin >> c1;
return 1;
}
cin >> c1;
r = palindrom(N - 2);
cin >> c2;
return r && (c1 == c2);
}
int
main() {
int N;
cin >> N;
cout << "Sequence was " << (palindrom(N) ? "" : "not ")
<< "a palindrom." << endl;
return 1;
}