试图写一个程序来理解pre和;后增量和一元运算符

时间:2015-04-10 14:07:58

标签: c#

using System;
namespace UnaryOperators
{
    class UnaryOperators
    {
        //pre and post incerment checking and examples
        public int a=0;

        public int PreIncrement()
        //shows error here(not all code paths return value)
        {
            //what i am trying to do here is i want to create 2 methods 
            //one for pre increment and other for post increment
            //but when i am typing program i stuck with above error so 
            //i didn't complete the code 
            //i want to know how pre increment and post incerment work 
            for(a = 0; a < 10; a++)
            {
                Console.WriteLine("PreIncrement value of a is "+a);
                return a;
            }
        }
        public static void Main(string[]args)
        {
            /*
            //if any one gives me a program as an example i will be really thankful
            //please give me an example to understand pre and post increments 
            // if you can understand anything of my code help me solve it
            // (but honestly think my code is shit)
            */
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这个小程序显示了前后增量的工作原理。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("After pre {0}", PreInc());
        Console.WriteLine();
        Console.WriteLine("After post {0}", PostInc());
        Console.ReadLine();
    }

    public static int PreInc()
    {
        int a = 0;

        do {
            Console.WriteLine("PreIncrement value of a is {0}", ++a);
        } while (a < 10);

        return a;
    }

    public static int PostInc()
    {
        int a = 0;

        do {
            Console.WriteLine("PostIncrement value of a is {0}", a++);
        } while (a < 10);

        return a;
    }
}