Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

c# - "Not all code paths return a value"

I'm working with arrays and methods. I'm working on writing a code that will calculate the average of numbers entered by user in an array. I came up with the first method but VS tells me that "not all code paths return a value". When I tested the code in the Main() method it works well but when it's inside my GetValues() method i get the error.

I read all other posts but they not quite make sense to me because of their specificity. I know this isn't too difficult but I'm a beginner and trying to understand this myself.

My program isn't done yet, the following code is just the first part (method) of my program. Once GetValues () work, the idea is then to call this method from another method that will calculate the average. Again, GetValues() is supposed to capture the array.

Here's the code:

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];
            }
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Are you trying to return the integer array score?

   ....
        for (int i = 0; i < score.Length; i++)
        {
            total += score[i];
        }
        return score;
    }

So you can capture this array when you call it like so

int[] scores = GetValues();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...