首页 > 解决方案 > Why does my loop stop when a condition is met

问题描述

I have to write a loop that returns "Fizz" if a number is a multiple of 3 and "Buzz" if it's a multiple of 5 between a certain set of number (here numbers between 15 to 22). When I execute the code, it only does the loop once and only returns "Fizz" whereas 15 is a multiple of both 3 and 5. How can I fix the issue? It needs to print out the numbers that are either a multiple of 3, of 5 or both and say if it's fizz, buzz or both Thanks,

class Program
{

  static void Main(string[] args)
  {
    Console.WriteLine(FizzBuzz(15, 22)); 
  }

  static string FizzBuzz(int première, int dernière)
  {
    string message = "";

    if (première < dernière)
    {

      while (première <= dernière)
      {

        if ( EstDivisiblePar3(première) )
        {
          message = "Fizz";
          return message;
        }

        if (EstDivisiblePar5(première))
        {
          message = "Buzz";
          return message;
        }

        première = première + 1;

      }
                
    }
    else
    {
      message = "« Incohérence des paramètres de FizzBuzz ».";
    }

    return message;
  }

  static bool EstDivisiblePar3(int première)
  {
    return (première % 3) == 0;
  }

  static bool EstDivisiblePar5(int première)
  {
    return (première % 5) == 0;
  }

}

标签: c#loopswhile-loop

解决方案


把它分成几部分!(这是有效编程的关键)

首先编写一个方法来确定要为数字显示什么字符串。

static string GetString(int n)
{        
    if (EstDivisiblePar3(n) && !EstDivisiblePar5(n))
    {
        return "Fizz";
    }
    if (!EstDivisiblePar3(n) && EstDivisiblePar5(n))
    {
        return "Buzz";
    }
    if (EstDivisiblePar5(n) && EstDivisiblePar3(n))
    {
        return "Fizz Buzz";
    }
    return n.ToString();
}

现在你的主程序非常简单:

static void FizzBuzz(int première, int dernière)
{
    for ( n = première; n <= dernière; n++ )
    {
        var message = GetMessage(n);
        Console.WriteLine(message);
    }
}

推荐阅读