0

/* 你好我是一名学生,试图做一些练习编程任务,但我似乎无法让我的一个变量在函数中工作,我需要用户输入变量的值,但它想要我们在 PowerOf 函数而不是 Main 函数中声明它,很抱歉成为 n00b,但任何帮助将不胜感激。[:*/

using System;

namespace ThePowerOf
{
    class MainClass
    {
        public static void Main (string[] args)
        {

            string sUserInput;
            int iUserNum1 = 0;
            int iUserNum2 = 0;
            int iPower = 0;

            Console.WriteLine ("Enter a number");
            sUserInput = Console.ReadLine();
            iUserNum1 = Int16.Parse(sUserInput);

            Console.WriteLine ("Enter a number");
            sUserInput = Console.ReadLine();
            iUserNum2 = Int16.Parse(sUserInput);

            iPower = PowerOf(iUserNum1);

            Console.WriteLine((iUserNum1) + (" To the power of ") + (iUserNum2) + (" = ") + (iPower));
            Console.ReadLine();

        }

        static int PowerOf(int iUserNum1)

        {   

        for (int i = 0; i < iUserNum2; ++i)

        {

        iUserNum1 = (iUserNum1 * iUserNum1);

        }       

        return iUserNum1;   

        }

    }
}
4

2 回答 2

1

您的函数声明方式错误,如何通过传递单个参数来计算提高到数字的幂(除非其中一个值是常数)

固定方法减速:

    static int PowerOf(int iUserNum1, int iUserNum2)
    {
        int result = 1;
        for (int i = 0; i < iUserNum2; i++)
        {
            result = result*iUserNum1;
        }
        return result;
    }

并改变你调用函数的方式,用 2 个参数正确调用它!

    static void Main()
    {
        string sUserInput;
        int iUserNum1 = 0;
        int iUserNum2 = 0;
        int iPower = 0;

        Console.Write("Enter a number : ");
        sUserInput = Console.ReadLine();
        iUserNum1 = Int32.Parse(sUserInput); // iUserNum1 is declared as 'int' so Int32.Parse()

        Console.Write("Enter a number to waise power to :");
        sUserInput = Console.ReadLine();
        iUserNum2 = Int32.Parse(sUserInput); // iUserNum2 is declared as 'int' so Int32.Parse()

        iPower = PowerOf(iUserNum1, iUserNum2);

        Console.WriteLine(iUserNum1 + " To the power of " + iUserNum2 + " = " + iPower);
        Console.ReadLine();
    }
于 2013-02-17T04:23:35.063 回答
0

将您的声明移至iUserNum2班级级别:

class MainClass
{
    int iUserNum2 = 0; // PUT IT HERE
    public static void Main (string[] args)
    {

方法中声明的变量不共享。在类中声明的变量是共享的(前提是它们是非静态的并且在非静态方法中使用......但这是供您稍后学习的)。

于 2013-02-17T04:23:45.047 回答