Skip to main content
 首页 » 编程设计

c#之在另一个方法中使用 Main 方法中的变量

2024年02月06日12bluestorm

我目前正在完成一项任务,只是想得到一些帮助。对于我的代码,我必须从值数组中找到最低值和最高值,然后将不是最高值或最低值的值加在一起(例如,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) { ...} 
}