c# - 卡住循环/迭代 [升 C]
问题描述
我正在尝试创建一个循环,当我键入“ok”时,它将添加所有输入的数字并显示所有输入数字的总和。如果你能给我一个方法,那就太好了。谢谢你。
class Program
{
static void Main(string[] args)
{
{
int sum = 0;
while (true) {
Console.WriteLine("Please enter a number: \n");
int num;
if (int.TryParse(Console.ReadLine(), out num))
{
{
if (num == 0)
{
break;
sum += num;
}
}
}
else if (Convert.ToString(num) == "ok")
{
Console.WriteLine("Sum is " + sum);
break;
}
}
}
}
}
}
解决方案
这是一个解决方案,请在复制粘贴之前阅读 C# 基础知识。
// Setup our variables
string input;
var total = 0;
// Begin a loop running forever
do
{
// Get the user input as a string - the code has no idea it is a number at this point
Console.Write("Input a number: ");
input = Console.ReadLine();
// See if we can parse the string into a number, this function returns a boolean, hence if the string is an int, the `total += value` block is executed
if (int.TryParse(input, out var value))
{
total += value;
}
else if (input.ToLower() != "ok")
{
// If the input string is not an int, and the input is not "ok" then, let them know their input was not a number
Console.WriteLine("Please input a number...");
}
else
{
// The input string was not an int, but it was the string "ok", therefore break out of this loop
break;
}
} while (true);
// After breaking out of the loop, print the total
Console.WriteLine(total);
推荐阅读
- c++ - 使用位掩码和指针从 int 中保存一个字节
- javascript - 为什么异步函数返回未定义?
- android - 将华为身份验证添加到使用 Firebase 身份验证的现有应用程序
- c++ - 哪个 DLL 导出 NtGdiBeginGdiRendering 函数以及如何导出?
- json - Flipper的(调试平台)日志数据默认折叠
- java - 如何生成动态按钮取决于 Firebase 中的数据量
- vb.net - 为什么我的 VB 代码会收到此特定错误消息?
- android - 后退按钮和浏览器
- go - 是否可以为两个子结构共享一种方法
- reactjs - 类型错误:_data_homezone_json__WEBPACK_IMPORTED_MODULE_3__.data.map 不是函数