亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從函數訪問數組整數

從函數訪問數組整數

C#
SMILET 2022-11-21 17:01:21
我正在嘗試在函數中寫入數組中的整數,它總是顯示“當前上下文中不存在名稱'(數組名稱)'”int counter = int.Parse(Console.ReadLine()); int[] nums = new int[counter];while (counter > 0){    nums[counter] = counter;    counter--; } (基本上創建了一個長度為用戶選擇的數組,并將數字從 1 到數組中的計數器) 在一些更改數組整數中的內容的代碼之后 (計數器不會更改)print(counter);我創建的一個函數public static void print(int count);{    *some code*    while (count > 0)    {        Console.WriteLine(nums[count]); //line with the error        count--;    } }我期待它在 nums 數組中寫入整數,但它沒有。(順便說一句,我需要把它寫在函數里面,我稍后在代碼中調用它)
查看完整描述

2 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超22個贊

好吧,這意味著您的數組不在函數的上下文中,因此它無法“看到”它。您要么必須在函數中聲明它,要么通過類中的某個字段訪問它,要么將其作為參數傳遞

public static void print(int[] nums, int count)、
{...}


查看完整回答
反對 回復 2022-11-21
?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

“名稱‘(數組名稱)’在當前上下文中不存在”


由于錯誤表明您的函數無法在函數上下文中找到數組(因為它在函數本身之外)。


為了找到它,您有兩種選擇:


print(counter, nums)

public static void print(int count, int[] nums)

{...}

或者將所有內容包裝在一個類中:


class Program

{

    static int[] nums; 

    static void Main(string[] args)

    {

        int counter = int.Parse(Console.ReadLine());

        int[] nums = new int[counter];

        while (counter > 0)

        {

            nums[counter] = counter;

            counter--;

        }

        print(counter);

    }

    public static void print(int count)

    {

        // some code

        while (count > 0)

        {

            Console.WriteLine(nums[count]); //line with the error

            count--;

        }

    }

}


查看完整回答
反對 回復 2022-11-21
  • 2 回答
  • 0 關注
  • 108 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號