Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: C# finding a whole number  (Read 11045 times)

0 Members and 1 Guest are viewing this topic.

-kat-

  • Guest
C# finding a whole number
« on: February 21, 2010, 08:47:10 AM »
Hi I was hoping someone might be able to help me.

I have to write a program in C#. part of that program is finding out whether a year is a leap year or not. Now I know that if you divide the year by 4 and it comes back with a whole integer number that it is a leap year.

My question is how can I check that the number it comes back with is a whole integer number?

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: C# finding a whole number
« Reply #1 on: February 21, 2010, 09:04:05 AM »
Now I know that if you divide the year by 4 and it comes back with a whole integer number that it is a leap year.
First- this is actually not the entire rule.

A year is a leap year if it's evenly divisible by 4 but not by 100


if (year modulo 4 is 0) and (year modulo 100 is not 0) or (year modulo 400 is 0)
       then is_leap_year
else
       not_leap_year


Anyway- the answer to your problem is the C# modulus operator, %: for example, this function would determine if a year was a leapyear:


Code: [Select]
private bool IsLeap(int year)
        {
            if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
                return true;
            else
                return false;
   
        }
However- a better solution is to simply use the .NET framework. System.DateTime.IsLeapYear(int) will tell you if a specified year is a leap-year.
I was trying to dereference Null Pointers before it was cool.

Salmon Trout

  • Guest
Re: C# finding a whole number
« Reply #2 on: February 21, 2010, 09:23:38 AM »
However- a better solution is to simply use the .NET framework. System.DateTime.IsLeapYear(int) will tell you if a specified year is a leap-year.

Better - but not so much math practice involved... the teacher of the C# class might give -kat-'s homework a low mark if he or she did that!

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: C# finding a whole number
« Reply #3 on: February 21, 2010, 10:56:52 AM »
Better - but not so much math practice involved... the teacher of the C# class might give -kat-'s homework a low mark if he or she did that!



Yes, that's why I included the other stuff :).
I was trying to dereference Null Pointers before it was cool.