c# - 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;
}
}
解决方案
把它分成几部分!(这是有效编程的关键)
首先编写一个方法来确定要为数字显示什么字符串。
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);
}
}
推荐阅读
- android - 使用设备凭据时 Android 生物识别无法导航
- python - 比特币出售或购买带有颜色的显示器(在 cmd/win10 中)
- php - 如何在 $row->variable 的末尾添加变量 Count?
- html - 如何在 div 内的按钮上显示手形光标?
- google-sheets - 根据同一工作簿中其他工作表中的数据提供汇总表
- sql-server - 如何在不使用 CSV 的情况下将数据从 Tableau 推送到 SQL Server
- python - 填充部分文本后如何单击自动完成?
- orm - 使用 Sequelize 连接 3 个表
- python - 如何从2个同名的python文件中加载2个同名的函数?
- javascript - 将对象推入数组的正确方法是什么?