首页 > 解决方案 > 如何从 if 语句中返回值?

问题描述

我不仅对 C# 而且对整个编程都很陌生,我知道这是一个非常基本的问题,但我只是不知道如何从 if 语句中返回一个值。这是我的代码:

static void Main(string[] args)
{
    int couscous = RandomNumber(1);
    Random rnd = new Random();
    while (couscous > 1)
    {
        int remainder = couscous % 3;
        if (remainder == 0)
        {
            Console.WriteLine(couscous / 3);
            int step2 = couscous / 3;
           // I want to return couscous / 3 to the beginning of the while statement so it repeats all the code but with step2 instead of couscous.
        }
        else if (remainder != 0)
        {
            Console.WriteLine(couscous + 1);
        }
    }
}

static int RandomNumber(int i)
{
    Random rnd = new Random();
    i = rnd.Next(1, 1000);
    int input = i;
    return input;

标签: c#if-statement

解决方案


你的意思是这个,你也会了解更多关于return的信息。
因为 void 不能有回报。

using System;
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ifReturn());
        }

        static string ifReturn()
        {
            bool good = true;
            if (good)
            {
                return "It was true";
            }
            else
            {
                return "It was false";
            }
        }
    }
}

推荐阅读