D
davy.zou
#include <iostream.h>
#include <math.h>
void centscalculation(int cents, int &count2, int &count7, int
&count9) {
int Total, diff, mindiff=999999, x, y, z, Nstamp, NewNstamp=999999;
//x is for 9cents, y is for 7cents, z is for 2cents;
for(x=cents/9; x>=0; x--) {
for(y=(cents-x*9)/7; y>=0; y--) {
z=(cents-x*9-y*7)/2;
Total=(z*2+y*7+x*9);
if (Total>=cents) {
} else {
Total=Total+2;
z=z+1;
}
diff=Total-cents;
if (diff<mindiff) {
mindiff=diff;
count2=z;
count7=y;
count9=x;
} else if (diff==mindiff) {
Nstamp=x+y+z;
NewNstamp=count2+count7+count9;
if (Nstamp<NewNstamp) {
count2=z;
count7=y;
count9=x;
}
}
}
}
}
void main () {
int cents;
int count2, count7, count9;
while (true) {
cout<<"Enter cents, 0 to terminate: "<<endl;
cin>>cents;
if (cents<0) {
cout<<"Error."<<endl;
continue;
}
if (cents==0) {
break;
}
centscalculation(cents, count2, count7, count9);
cout<<"answer is "<<count2<<" 2 cents stamps "<<count7<<" 7 cents
stamps "<<count9<<" 9 cents stamps."<<endl;
cout<<"The total number of stamps is "<<count2+count7+count9<<endl;
}
}
#include <math.h>
void centscalculation(int cents, int &count2, int &count7, int
&count9) {
int Total, diff, mindiff=999999, x, y, z, Nstamp, NewNstamp=999999;
//x is for 9cents, y is for 7cents, z is for 2cents;
for(x=cents/9; x>=0; x--) {
for(y=(cents-x*9)/7; y>=0; y--) {
z=(cents-x*9-y*7)/2;
Total=(z*2+y*7+x*9);
if (Total>=cents) {
} else {
Total=Total+2;
z=z+1;
}
diff=Total-cents;
if (diff<mindiff) {
mindiff=diff;
count2=z;
count7=y;
count9=x;
} else if (diff==mindiff) {
Nstamp=x+y+z;
NewNstamp=count2+count7+count9;
if (Nstamp<NewNstamp) {
count2=z;
count7=y;
count9=x;
}
}
}
}
}
void main () {
int cents;
int count2, count7, count9;
while (true) {
cout<<"Enter cents, 0 to terminate: "<<endl;
cin>>cents;
if (cents<0) {
cout<<"Error."<<endl;
continue;
}
if (cents==0) {
break;
}
centscalculation(cents, count2, count7, count9);
cout<<"answer is "<<count2<<" 2 cents stamps "<<count7<<" 7 cents
stamps "<<count9<<" 9 cents stamps."<<endl;
cout<<"The total number of stamps is "<<count2+count7+count9<<endl;
}
}