Use long type to host large value - CSharp Language Basics

CSharp examples for Language Basics:long

Description

Use long type to host large value

Demo Code


using System;/*  ww  w.j  ava2s.  co  m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
   static void Main(string[] args)
   {
      int million = 1000000;
      // 1. Crash at least, we do not definitely want a nonsense
      try
      {
         long result = million * million;
         Console.WriteLine("Million times million:" + result);
      }
      catch (Exception)
      {
         Console.WriteLine("I cannot calculate this.");
      }
      // 2. Correct calculation of a big value
      long millionInLong = million;
      long correctResult = millionInLong * millionInLong;
      Console.WriteLine("Million times million: " + correctResult.ToString("N0"));
      long correctResultAlternatively = (long)million * (long)million;
      Console.WriteLine("Million times million: " + correctResultAlternatively.ToString("N0"));
   }
}

Related Tutorials