Convert 1000 months in 83 years and 4 months - c#

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);
}

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.
}

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.

Related

How to do the loop and solve the following

I'm supposed to code a program that writes out a division just like in school.
Example:
13:3=4.333333333333
13
1
10
10
10....
So my approach was:
Solve the division then get the solution in a List.
Then question if the first number (in this case 1) is divisible by 3.
If not put it down and add the second number and so on...
I managed to do this the first time. It's sloppy but works. The problem is that it only works with numbers that when divided get to have a decimal in it.
Exapmle:
123:13
This is the first code:
do
{
for (int number = 1; number <= divNum; number++)
if (number % divisor == 0) countH++;
for (int i = 0; i < count; i++)
Console.Write(" ");
if ((c = divNum % divisor ) < divisor )
{
Console.WriteLine(" " + ((divNum- (countH * divisor ))) * 10);
}
else Console.WriteLine(" " + (divNum- (countH * divisor )));
c = divNum % divisor ;
if (c < divisor )
{
divNum = c * 10;
}
count++; countH = 0;
} while ((divNum >= divisor ) && (count < x));
Any ideas or help? Sorry if this is a bad question.
************ added
Try of a better explanation:
1 cant be divided by 13, so it goes down, we get the 2 down and try 12 divided by 13, still nothing so we get the 3 down and try 123:13, 13 goes 9 times in 123 so we have 123-9*13 = 6 the six goes down we write 9 in the result. We try 6:13 not going so we drop a 0 next to 6. Next we try 60:13, 13 goes 4 times so 60-4*13 = 8, we get the 8 down. And so on..
123:13=9.46153....
123
60
80
20
70
50
....
Something like this should work. Not the fastest solution most likely, but should do the job.
var number = 123;
var b = 12;
int quotient;
double remainder = number;
var x = 10;
do
{
quotient = (int)Math.Floor(remainder / b);
remainder = remainder - (quotient * b);
for (int i = 0; i < count; i++)
Console.Write(" ");
remainder *= 10;
Console.WriteLine(" " + remainder);
count++;
} while ((remainder > 0) && (count < x));

calculate less number of hops C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Good morning :) I'm working on C# and I want to write a code that can calculate the less number of hops from any point to particular point, as a picture show
click here to show the picture
I have points from 1 to 12, so if I want to calculate the less number of hops from the point 12 to 1 it will be 1 with counterclockwise not 11 hops with clockwise.
another example to clarify my question, if I want to calculate the less number of hops from the point 11 to 4 it will be 5 with counterclockwise not 6 hops with clockwise. notice : the number of points may be an odd number.
I hope you understand my question ..
Try clockwise, anticlockwise and take minimum:
private static int Hops(int a, int b) {
return Math.Min((12 + a - b) % 12, (12 + b - a) % 12);
}
Tests:
// 5
Console.WriteLine(Hops(11, 4));
// 1
Console.WriteLine(Hops(12, 1));
Edit: As Matthew Watson has mentioned in comments, you may want to know whether it clockwise or anticlockwise:
private static int ClockwiseHops(int a, int b) {
return (12 + b - a) % 12;
}
private static int AntiClockwiseHops(int a, int b) {
return (12 + a - b) % 12;
}
private static int Hops(int a, int b) {
return Math.Min(ClockwiseHops(a, b), AntiClockwiseHops(a, b));
}
private static String Solve(int a, int b) {
int hops = Hops(a, b);
if (hops == ClockwiseHops(a, b))
return String.Format("{0} -> {1} (clockwise) {2} hops", a, b, hops);
else
return String.Format("{1} -> {0} (anticlockwise) {2} hops", a, b, hops);
}
Tests:
// 12 -> 1 (clockwise) 1 hops
Console.WriteLine(Solve(12, 1));
// 11 -> 4 (clockwise) 5 hops
Console.WriteLine(Solve(11, 4));
Have you considered the % Modulo Operator? That will give you the remainder of of the first number divided by the second. For example:
6 % 3 = 0 (3 goes into 6 exactly twice so zero remaining)
10 % 4 = 2 (4 goes into 10 twice with a remainder of two)
So you will want to try both routes and then check which one is smaller.
so try:
int numberOfPositions = 12;
Math.Min ((numberOfPositions + b - a) % numberOfPositions, (numberOfPositions + a -b) % numberOfPositions);
If you would like to see how modulo calculations work then there's an online calculator here:
http://www.miniwebtool.com/modulo-calculator/
Is it this simple?
int NUM_OF_NODES = 12;
int numOfHops = NUM_OF_NODES;
int point1 = 11;
int point2 = 4;
int path1 = Math.Abs(point1 - point2);
int path2 = numOfHops - path1;
int result = path1 < path2 ? path1 : path2;
return result;
For simple function
public int getLeastPath(int point1, int point2)
{
int path1 = Math.Abs(point1 - point2);
int path2 = NUM_OF_NODES - path1;
return path1 < path2 ? path1 : path2;
}
EX : 11-8
1.Get the mod of first number and last number
11% 12 = 1
8 % 12 = 8
add the sum
if it is less than 12 > 1 + 8 = 9
else sub
subtract with the 12 -9 = 3
compare 9 with 3, lesser value will be the answer.
The easiest answers were already provided but here's a recursive function, that actually "jumps" from one number to the other:
Func<int, int, int, int> Hop = null;
Hop = (direction, start, end) =>
{
if (start < 1)
start = 12;
if (start != end)
return 1 + Hop(direction, (start + direction), end);
return 0;
};

Overcoming a discrepancy in a division

I have the following code to divide an amount by a number and allocate the result as an amount that needs to be paid per month.
objData.month_per_amount = (Convert.ToDecimal(txtAmount.Value) / Convert.ToInt32(txtMonths.Value));
In a scenario example if I divide 13 by 3 and round off the result to 2 decimal places I get 4.33 for each month. But when I multiply 4.33 by 3 I am getting 12.99, which is not equivalent to 13. There is a discrepancy of 0.01. In this scenario how can I allocate like below:
month 1: 4.33
month 2: 4.33
month 3: 4.34
Hope I made it clear, the preferred code should only be executed if there is such a discrepancy, for example if 14 is to be divided by 2, we get 7 for each month and 7+7=14, so exactly the same figure we are getting here.
In accounting you'd often use something called 'reducing balance' for this. The idea is that you calculate the month's total, deduct it from the overall total and reduce the number of months. So something like:
decimal balance = 13m;
int months = 3;
int monthsRemaining = 3;
for (var i = 0; i < months; i++)
{
decimal thisMonth = Math.Round(balance / monthsRemaining, 2);
balance -= thisMonth;
monthsRemaining -= 1;
Console.WriteLine("Month {0}: {1}", i + 1, thisMonth);
}
This will result in 4.33, 4.34, 4.33.
The benefit of this method is that the rounding errors are distributed fairly evenly throughout the period rather than all in one month. For example, 100 over 24 months using that method would result in 23 payments of 4.17 and 1 of 4.09 whereas reducing balance would be 4.16 or 4.17 each month.
You do not have to check the remainder. A more efficient C# code (in terms of the required computation) would be like the following.
double amount = 13;
int months = 3;
int precision = 2;
double[] amountForEachMonth = new double[months];
double temp = Math.Round(amount / months, precision);
for (int i = 0 ; i < months - 1 ; i++)
amountForEachMonth[i] = temp;
amountForEachMonth[months - 1] = amount - (temp * (months - 1)) ;
You don't need to make it a special case when there is a discrepancy, you can simply always calculate the payment of the last month as what's left to pay to reach the total amount. If there is no discrepancy then it will be the same value anyway. Example:
int months = Convert.ToInt32(txtMonths.Value);
decimal amount = Convert.ToDecimal(txtAmount.Value);
month_per_amount = Decimal.Round(amount / months, 2);
decimal last_month = amount - (months - 1) * month_per_amount;
for (int month = 1; month <= months; month++) {
decimal monthly = month < months ? month_per_amount : last_month;
Console.WriteLine("Month {0}: {1}", month, monthly);
}
if " amount % month == 0 " , no discrepancy occures. otherwise, the last item should be a little more than others .
(The code here may have some syntax issues, I wanted to show you the algorithm.)
decimal amount = Convert.ToDecimal(txtAmount.Value);
int month = Convert.ToInt32(txtMonths.Value);
int n = 3;
decimal amounts[3];//n = 3
for (int i = 0 ; i < n-1 ; i++)
amounts[i] = amount / month;
if ( amount % month != 0 ) {
amounts[n-1] = amount - ( amount / month * (n-1) ) ;
else
amounts[n-1] = amount / month ;

Looping - amount of years from months

I have a int months (84 for example) and I need to work out how many years that equals so using 84 = 7 years
I need to loop through the initial number and see how many full years are in there and print the result
example:
int count = 84;
for (int i = 12; i <= count; i++)
{
years = i;
}
This doesn't work of course, it produces '84 years' where I should produce 7 years. I also need to get the remaining months after the year calculation so if the initial number was 85 for example it would result in 7 years 1 month.
Use standard mathematical operations instead of a loop:
int count = 84;
int years = count / 12;
int months = count % 12;
First one is division, second is modulus.
Because both count and 12 are integers count/12 returns an integer as well. So for 85 it will return 7, not 7.1.
Update
Loop version could look like that:
count = 84;
years = 0;
for (int i = 12; i <= count; i += 12)
{
years++;
}
Doing that with a loop would look like this:
int years = 0;
while (count >= 12) {
count -= 12;
years++;
}
However, you can do the same without looping:
int years = count / 12;
count %= 12;
Try this:
DateTime t = new DateTime();
t = t.AddMonths(84);
int year = t.Year; // year = 8
int month = t.Month; // month = 1
Surely you just need basic math operations:
int count = 84;
int years = (int)(count / 12);
int months = count % 12;
int years = count / 12;
int remainingMonths = count % 12;
thanks to everyone who gave a answer :D much appreciated
i got it working like this in the end
int employmentInMonthsAmount = this.MaxEmploymentHistoryInMonths;
var intcounter = 0;
int years = 0;
for (var i = 0; i < employmentInMonthsAmount; i++)
{
if (intcounter >= 12)
{
years++;
intcounter = 0;
}
intcounter++;
}
var monthsleft = intcounter;

C# Formatting Age - Regarding Days, Weeks , Months - Years

I am working on some medical software and I am required to output all ages in a very specific manner, based on the following rules:
If under 6 Weeks old : ###D (Number of Days)
If under 6 Months old : ###W (Number of Weeks)
If under 2 Years old : ###M (Number of Months)
If above 2 Years old : ###Y (Number of Years)
Using C# I am trying to find a simple method of doing this just using a Person's Date of Birth, any help would be greatly appreciated.
I was working on something similar yesterday, but something like this should suit your needs: (assuming 7 day weeks, 31 day months, 365 day years etc.)
Revised Method : (Fixed as per Bob's suggestions)
public static string ConvertAge(DateTime dob)
{
DateTime today = DateTime.Today;
string fmt = "{0:0##}{1}";
//Greater than 2 Years old - Ouput Years
if (dob <= today.AddYears(-2))
return string.Format(fmt, (dob.DayOfYear <= today.DayOfYear) ?
(today.Year - dob.Year) : (today.Year - dob.Year)-1, "Y");
//Less than 2 Years - Output Months
if (dob < today.AddMonths(-2))
return string.Format(fmt, (dob.DayOfYear <= today.DayOfYear) ?
(today.Year - dob.Year) * 12 + (today.Month - dob.Month) :
((today.Year - dob.Year) * 12 + (today.Month - dob.Month))-1 , "M");
//Less than 2 Months - Output Weeks
if (dob < today.AddDays(-2 * 7))
return string.Format(fmt, (today - dob).Days / 7, "W");
//Less than 2 Weeks - Output Days
return string.Format(fmt, (today - dob).Days, "D");
}
Previous Method :
public string ConvertAge(DateTime dateOfBirth)
{
int daysOld = (DateTime.Now - dateOfBirth).Days;
//Age < 6 Weeks
if (daysOld < (6 * 7))
return String.Format("{0:0##}{1}", daysOld, 'D');
//Age < 6 Months
else if (daysOld < (6 * 31))
return String.Format("{0:0##}{1}", daysOld/7, 'W');
//Age < 2 Years
else if (daysOld < (2 * 365))
return String.Format("{0:0##}{1}", daysOld / 31, 'M');
//Age >= 2 Years
else
return String.Format("{0:0##}{1}", daysOld / 365, 'Y');
}
Hope this helps!
A DateTime type can be subtracted from other DateTimes, resulting in a TimeSpan representing the gap. Try this:
var timeAlive = DateTime.Today - dateOfBirth.Date;
Then, look at the Days, Months and Years (divide Days by 7 for Weeks) of timeAlive, and format accordingly.
The following makes no assumptions about days/months or year.
On the downside, it is not Y3K compatible.
public static string GetAge (DateTime dob) {
DateTime today = DateTime.Now;
string fmt = "{0:0##}{1}";
if (dob < today.AddYears(-2)) return string.Format(fmt, today.Year - dob.Year, "Y");
if (dob < today.AddMonths(-6))return string.Format(fmt, (today.Year - dob.Year)*12 + (today.Month - dob.Month), "M");
if (dob < today.AddDays(-6 * 7)) return string.Format(fmt, (today - dob).Days/7, "W");
return string.Format(fmt, (today - dob).Days, "D");
}
You can get an object representing the user's current age with a simple subtraction:
TimeSpan age = DateTime.Now - dateOfBirth;
And then it's just a matter of doing a bunch of if clauses
if (age.TotalDays < 6 * 7) // 6 weeks
// ...
else if (age.TotalDays < 6 * 30) // 6 months
// ...
// et cetera
You should be able to figure out how to do your formatting.

Categories

Resources