我正在處理數組和方法。我正在編寫一個代碼,用於計算用戶在數組中輸入的數字的平均值。我想出了第一種方法,但VS告訴我「不是所有的代碼路徑都返回一個值」。當我在Main()方法中測試代碼時,它運行良好,但是當它在我的GetValues()方法中時,我得到錯誤。「不是所有的代碼路徑都返回一個值」
我讀過所有其他帖子,但他們對我來說不太合理,因爲它們的特異性。我知道這不是太困難,但我是一個初學者,並試圖自己理解這一點。
我的程序還沒有完成,下面的代碼只是我的程序的第一部分(方法)。一旦GetValues()工作,那麼想法就是從另一個計算平均值的方法調用這個方法。再次,GetValues()應該捕獲數組。
下面的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testscores
{
class Program
{
static void Main(string[] args)
{
}
private static int[] GetValues()
{
string inValue;
int[] score = new int[5];
int total = 0;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Score {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
}
}
}
謝謝你,這正是我所做的。現在,如果我想從另一個方法調用返回的值。我應該向方法頭添加一個參數嗎?例如:private static int [] GetValues(int score) – okr
@Oskar不,這意味着你的意思是將一個int傳入你的方法,你可以通過名字得分來訪問......你不需要傳遞任何東西在,你正在創建一個名爲score – heisenberg
@kekekela的本地數組謝謝!因此,如果我想從另一個方法調用存儲在GetValues()中的值,我應該只是稱它爲從該方法鍵入「GetValues」?希望我在解釋我自己 – okr