1.

Solve : Problem with C++ code?

Answer»

Hey guys me again. I am currently working on a program in C++ that is supposed to output the cash total for an international phone call. There is a connection fee, which is $1.99, for the FIRST 3 minutes it's $2.00, and any additional minute it's $0.45 per minute after the first three minutes. I have it working and all and right when you run it, it displays "Enter the number of minutes the call lasted", so I enter a 1 or a 2 and it says "1.99" as it should, when i enter a 3 it reads "3.99" as it should, but then when i enter a four, it skips "4.44" and goes straight to "4.89" but continues from there correctly. The only prob is that it skips 45 CENTS when you enter anything higher than a 3. Here's my program and I have been using Visual Studio 2008 recently. Oh, and also I can't get the ELSE IF statement to take effect. Thx

#include
#include

using namespace std;

int main()
{
CONST double connectFee = 1.99;
double amtDue;
double addMin = 0.45;
int threeMin[] = {3, 2};
int minutes, i;
int addAmt;

i = 3;
amtDue = 0;
addAmt = threeMin[0] + 1;
cout << "Enter the number of minutes the call lasted: ";
cin >> minutes;
cout << endl;

if (minutes > threeMin[0])
{
amtDue = amtDue + connectFee + threeMin[1];

while (i <= minutes)
{
amtDue = amtDue + addMin[1];
i++;
}
}
if (minutes == threeMin[0])
{
amtDue = connectFee + threeMin[1];
}
if (minutes < threeMin[0])
{
if (minutes > 0)
amtDue = connectFee;
}
else if (minutes < 0)
{
cout << "--Invalid input--" << endl;
}
cout << amtDue << endl;

return 0;
}Sorry, on Line 28 the 'addMin[1]' shouldn't have the [1] in it. that looks a tad long for what it does.

here's what I came up with.

Code: [Select]#include <IOSTREAM>

using namespace std;
double GetCost(double CallLength);
int main()
{


double minutes;
cout << "Enter the number of minutes the call lasted: ";
cin >> minutes;
cout << endl;
cout << GetCost(minutes);
//following two lines are for pausing when the program is run from the IDE.
char inme;
cin >> inme;
return 0;
}
//GetCost; calculates the cost of a phone call of the given length.

double GetCost(double CallLength)
{
// connection fee of 1.99 is always charged...
long cost=199;
if (CallLength<=3)
cost=cost+200;
else if(CallLength>3)
{
cost=cost+200;
cost = (cost + (45*((double)CallLength-3)));
}
return ((double)cost)/100;
}

the issue with the original code can probably be solved by changing the code in the first if from:
Code: [Select] amtDue = amtDue + connectFee + threeMin[1];

while (i <= minutes)
{
amtDue = amtDue + addMin[1];
i++;
}
to something like:
Code: [Select]amtDue=connectFee+threeMin[1]+ ((double)addmin[1] * (double)(minutes-3));



Discussion

No Comment Found