user2669196
user2669196

Reputation: 175

C# program for printing out copies

My program is taking 2 dollars for each printed copy for the first 100 papers that is copied out. If the user prints out more than a hundread copies, for each copy that is above hundread it takes 1dollar per copy (So if I want to print out 101 copies, the price should be 200 + 1, 1 dollar for the 101:th copy and 2 dollars each for the first 100 copies). Here is my Code:

int CopyCost = 2;
        int ammountOfCopies;
        int discount = 1;
        Console.WriteLine("How many copies would you like?: ");
        ammountOfCopies = int.Parse(Console.ReadLine());


        for (int i = 0; i < ammountOfCopies; i++)
        {
        if (ammountOfCopies > 100)
            CopyCost = 2 - discount;
        else
            CopyCost =  2;

        CopyCost *= ammountOfCopies;
        }
        Console.WriteLine("The total cost for your copies is: {0} ", CopyCost);

        Console.ReadLine();

But the problem I have is, if I choose to write out 101 copies, it discounts every copy to 1 dollar, and not only the one above 100.

Upvotes: 2

Views: 246

Answers (4)

Jonathan Wood
Jonathan Wood

Reputation: 67273

Or if you prefer a one-liner:

price = (copies * 2) - Math.Max(copies - 100, 0);

Upvotes: 0

Anton Barycheuski
Anton Barycheuski

Reputation: 720

Better, use this code:

int TotalCost;

if (amountOfCopies > 100)
{
    TotalCost = (amountOfCopies - 100) * (CopyCost - discount) + 100 * CopyCost;
}
else
{
    TotalCost = amountOfCopies * CopyCost;
}

Console.WriteLine("The total cost for your copies is: {0} ", TotalCost);

Upvotes: 0

zimdanen
zimdanen

Reputation: 5626

You are looping over each of your copies (numberOfCopies, btw, not amountOfCopies) and applying the calculation each time. You should calculate directly instead; there's no need for a loop in this situation:

if (numberOfCopies > 100)
{
    CopyCost = 200 + (numberOfCopies - 100);
}
else
{
    CopyCost = 2 * numberOfCopies;
}

Upvotes: 0

driis
driis

Reputation: 164331

This is more a math problem than a coding one. You need to take the amount of copies at or below 100 and multiply it with the normal price. Then take the amount of copies over 100 and multiply with the discounted price. No need for the for loop.

Break the problem into small pieces in the code, for instance, like so:

int price = 2;
int discountedPrice = price - 1;
int amountAtNormalPrice = Math.Min(amountOfCopies, 100);
int amountAtDiscountPrice = Math.Max(amountOfCopies - 100, 0);
int amountTotal = (amountAtNormalPrice * price) + (amountAtDiscountedPrice * discountedPrice);

Upvotes: 8

Related Questions