Reputation: 7
I am writing a simple code for rental price calculation. My code should work like this (theoretically):
Base price = 300 (It is for 7 days) and when user increases days from 7 to for e.g 10 the price increases and when they decrease again from 10 to 8 the price decrease.
I am doing it with date time component in C# windows form
My Code:
int baseprice = Convert.ToInt32(label21.Text);
int price = days * baseprice* 0.3;
if (days >= 7)
{
int totalprice = baseprice + price;
label21.Text = Convert.ToString(totalprice);
}
This code is working but it is always increasing not decreasing it when the days got decreased
Upvotes: 0
Views: 317
Reputation: 102
First of all, I would try to use decimal type instead of integer.
Secondly, try to approach the logic differently. Try to caclulate price based on number of additional days. The code bellow is not ready, it needs a variable taken from UserInput.
int baseprice = Convert.ToInt32(label21.Text);
decimal unit_cost= baseprice/7;
decimal price = days *unit_cost;
int additional_days = 3; // use some variable input from user so it would be dynamic
if (days >= 7)
{
int totalprice = baseprice + unit_cost * additonal_days
label21.Text = Convert.ToString(totalprice);
}
Upvotes: 1
Reputation: 323
Do you want to do this?
int price = days * baseprice * 0.3;
int totalprice = baseprice + (days >= 7 ? price : 0);
label21.Text = totalprice.ToString();
or this?
int totalprice = (int)(days * baseprice / 7f);
label21.Text = totalprice.ToString();
Upvotes: 0