簡體   English   中英

在另一種方法中使用Main方法中的變量

[英]Use variable from Main method in another method

我目前正在做作業,只想在某些方面提供一些幫助。 對於我的代碼,我必須從值數組中找出最低和最高值,然后將那些不是最高或最低值的值相加(例如1、2、3、4、5-我會加2+ 3 + 4)

因此,盡管最好的方法是遍歷數組並記錄存儲最高/最低值的位置。 這是我遇到的問題,數組存儲在Main方法中,但是我還沒有找到在另一種方法中訪問它的方法。 到目前為止,我的代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scoring {
class Program {   
    static void Main(string[] args) {
        int[] scores = { 4, 7, 9, 3, 8, 6 };

        find_Low();

        ExitProgram();
    }

    static int find_Low() {
        int low = int.MaxValue;
        int low_index = -1;


        foreach (int i in scores) {

            if (scores[i] < low) {
                low = scores[i];
                low_index = i;

            }                
        }

        Console.WriteLine(low);
        Console.WriteLine(low_index);
        return low;  
    }

    static void ExitProgram() {
        Console.Write("\n\nPress any key to exit program: ");
        Console.ReadKey();
    }//end ExitProgram
}

}

我得到的錯誤是“名稱'分數'在當前上下文中不存在。任何提示/幫助將不勝感激。

為了使它盡可能簡單,請像這樣更改程序

class Program {

    static int[] scores = { 4, 7, 9, 3, 8, 6 };

    static void Main(string[] args) { ...}
}

將數組作為參數傳遞:

static int find_Low(int[] scores) { 
     //your code
    }

在MainMethod中:

static void Main(string[] args) {
    int[] scores = { 4, 7, 9, 3, 8, 6 };

    find_Low(scores);    //pass array

    ExitProgram();
}

您可以將數組作為參數傳遞給函數:

using System.IO;
using System.Linq;
using System;

class Program
{
    static void Main()
    {
        int[] scores = { 4, 7, 9, 3, 8, 6 };
        Console.WriteLine(resoult(scores));
    }

    static int resoult(int[] pScores)
    {
        return pScores.Sum() - pScores.Max() - pScores.Min();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM