I try to make something and its work, but when I try to make a date under 1 month its crash. Can someone help me? The code is like this:
int page = int.Parse(Console.ReadLine());
int campingDays = int.Parse(Console.ReadLine());
int pagesPerDay = int.Parse(Console.ReadLine());
int months = page / ((30 - campingDays) * pagesPerDay);
int years = months / 12;
int remainingMonths = months % 12;
Console.WriteLine("{0} years {1} months", years, remainingMonths);
That's how i solve the "0 years 1 months" problem. There you go!
int readedPages = (30 - campingDays) * regularDays;
if ((campingDays == 30) || (regularDays == 0))
{
Console.WriteLine("never");
}
else
{
double readDuration = Math.Ceiling(bookPages / (double)readedPages);
double years = (int)(readDuration / 12);
double remainingMonths =(readDuration % 12);
Console.WriteLine("{0} years {1} months", years, remainingMonths);
}
You would get divide by zero error whenever
campingDays
is 30 because of (30 - campingDays)
pagesPerDay
is - 0 The problematic line:
int months = page / ((30 - campingDays) * pagesPerDay);
You may want 2 if
statements to handle those cases.
Michal Ciechan is correct. (Just read your answer closely)
suggestion:
int _campingDaysAdj = 30 - campingDays;
if(_campingDaysAdj > 0 && pagesPerDay > 0)
{
int months = page / ((30 - campingDays) * pagesPerDay);
int years = months / 12;
int remainingMonths = months % 12;
Console.WriteLine("{0} years {1} months", years, remainingMonths);
}
else
{
//throw an exception or an error message etc.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.