c# - 如何在 c# 中的特定行上重新启动?
问题描述
我是初学者,我尝试用 C# 创建一个简单的计算器。我想要的是,当你完成一个操作时,你可以重新启动或不重新启动。这是我的代码:
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
// First number
Console.WriteLine("Enter a number");
double A = Convert.ToDouble(Console.ReadLine());
// Second number
Console.WriteLine("Enter another number");
double B = Convert.ToDouble(Console.ReadLine());
// Operator
Console.WriteLine("Enter the operator");
string C = Console.ReadLine();
// if you want to add
if(C == "+")
{
Console.WriteLine(A + B);
}
// if you want to remove
if(C == "-")
{
Console.WriteLine(A - B);
}
// if you want to multiply
if(C == "*")
{
Console.WriteLine(A * B);
}
// if you want to subdivide
if(C == "/")
{
Console.WriteLine(A / B);
}
// Ask if they want to restart or finish
Console.WriteLine("Want to do another operations? y/n");
string W = Console.ReadLine();
// Restart
if(W == "y")
{
// Return at the beginning
}
// Finish
if(W == "n")
{
Console.WriteLine("Enter a key to close");
Console.ReadKey();
}
}
}
}
在这里你可以看到哪些,当你完成你的操作时,你可以重新启动(我不明白如何)或完成。我的代码(和我的演讲)效率不高(我是意大利人)我不擅长编程,我正在努力自学。
解决方案
您的问题的具体答案,如何跳到具体行是:goto
您放置一个标签myLabel:
,然后当您想跳到那里时goto myLabel;
但是,goto 是邪恶的,必须避免,在大型程序中它使代码不可读并导致大量问题。
好的解决方案是创建一个循环并测试一个变量,如下所示:
bool execute = true;
while(execute)
{
//..your calculator code
Console.WriteLine("Want to do another operations? y/n");
string W = Console.ReadLine();
if(W == "n")
execute = false;
}
这使得代码更加干净和可读。
推荐阅读
- git - Git fetch 无法解决 git checkout 上的 pathspec 错误 -- *
- reactjs - 打字稿错误:类型中缺少属性“htmlType”
- javascript - 用Vue动态替换字符串的一部分
- excel - Excel公式返回表中每个类别(另一列)的最高分(来自一列)
- html - HTML中是否有属性“数据格式”?
- python - Arduino和Python之间的串行通信错误
- apache - 重写规则将查询字符串参数作为子域添加到 htaccess 中的 URL
- python - 熊猫:在字符串列中填充占位符
- javascript - jquery如何判断我点击的td是第一行还是最后一行,以及行索引和列索引?
- openstack - 为什么我的 Gnocchi 测量频率与设置的粒度不匹配