gpt4 book ai didi

c# - 如何在 if 语句中使用 != 和字符串数组?

转载 作者:太空宇宙 更新时间:2023-11-03 20:53:16 25 4
gpt4 key购买 nike

我是编码新手,所以这可能不是最好的做事方式。我只是编写代码来习惯它并更好地理解它。我试图制作一个可以在 Visual Studios 的 cmd 中运行的计算器。我正在尝试收集用户输入的数据,看看它是否是“+、-、* 或/”,如果是,那么它应该继续,但如果不是,那么他们应该收到一条消息并重试(我还没有写这部分代码)。我制作了一个“+、-、* 和/”数组,并试图告诉 if 语句,如果它不等于这些值,则应显示消息以重试,但它给了我一个错误,说你可以' 将 != 分配给字符串值。

        double user_Input;
string user_inputOperation;
double user_secondInput;
double answer;
string[] operations = { "+", "-", "*", "/" };

Console.WriteLine("Type in a number: " );
user_Input = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Type an operation(+, -, *, /): ");
user_inputOperation = Console.ReadLine();


if (user_inputOperation != operations) // problem occurs here
{
Console.WriteLine("That's not right, try: +, -, *, or /");
user_inputOperation = Console.ReadLine();
}


Console.WriteLine("Type in another number");
user_secondInput = Convert.ToDouble(Console.ReadLine());

if (user_inputOperation == "+")
{
answer = user_Input + user_secondInput;

Console.WriteLine("The answer is: ");
Console.WriteLine(answer);
}

Console.ReadKey();
}
}

最佳答案

你需要 array.contains 而不是 !=

if (!operations.Contains(user_inputOperation)  
{
Console.WriteLine("That's not right, try: +, -, *, or /");
user_inputOperation = Console.ReadLine();
}

关于c# - 如何在 if 语句中使用 != 和字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53147462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com