Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Why am I getting this error: not all code paths return a value?

hi im new to c# and was trying to code but getting error can anybody help me with this what am i doing wrong?

using System;
using System.Collections.Generic;
using System.Text;

namespace hodder
{
    class Program
    {
        public static void Main()
        {
            isHodder(3);
        }

        static int isHodder(int n)
        {
            int k = n;
            for (int i = 2; i <= n / 2;i++ )
            {
                if ((n % 1) == 0)
                {
                    return 0;
                }
                else
                {
                    for (int j = 2; j <= k;j++ )
                    {
                        if (n == (2^ j)  - 1)
                        {
                            return 1;
                        }
                        else
                        {
                            return 0;
                        }
                        k=(2^j)-1;
                    }
                }
            }
        }
    }
}

im getting error on " static int isHodder(int n) " 'hodder.Program.isHodder(int)': not all code paths return a value

and "Unreachable code detected " on "k=(2^j)-1"

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The first error, "not all code paths return a value" means there is a path that the code could follow where no value would be returned (ie: calling isHodder(1)). You need to return some value outside of the for loop. Additionally, since you have an if/else block inside the second for loop the line

k=(2^j)-1;

Will never be executed.

    static int isHodder(int n)
    {
        int k = n;
        for (int i = 2; i <= n / 2; i++)
        {
            if ((n % 1) == 0)
            {
                return 0;
            }
            else
            {
                for (int j = 2; j <= k; j++)
                {
                    if (n == (2 ^ j) - 1)
                    {
                        return 1;
                    }
                    else
                    {
                        return 0;
                    }
                    k = (2 ^ j) - 1;
                }
            }
        }
        return 0;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...