c# - C# 代码问题 - 代码无法正常工作
问题描述
我用 C# 写了一个基本的猜数字游戏。无论用户选择什么 var c ,似乎每次都会返回第三个选项(“错误的选择!请重试。”)。我正在尝试使用字符(s 而不是 1 和 w 而不是 2 等,用 c 作为字符串),但它给出了相同的结果。不知道哪里不好。
using System;
namespace Challanges
{
class Program
{
static int guess = 500;
static int low = 1;
static int high = 1000;
static bool cont = false;
static void Guess() //guesses and adjusts variables according to input.
{
int c;
Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
c = Convert.ToInt32(Console.Read());
if (c == 1)
{
high = 500;
guess = low + high / 2;
}
else if (c == 2)
{
low = 500;
guess = low + high / 2;
}
else if (c == 3)
{
Console.WriteLine("Congratulations!! We found your number!");
cont = true;
}
else
{
Console.WriteLine("Wrong choice! Please try again.");
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
Console.ReadKey();
Console.WriteLine("Think of a number");
if(cont == false)
{
Guess();
} else
{
Console.ReadKey();
}
}
}
}
解决方案
正如之前的评论中提到的,Console.Read()
返回一个字符代码。数字 1 的字符代码是 49,因此您的条件失败并执行 else 块。
你想要做的是使用Console.ReadLine()
它返回一个字符串而不是字符代码。如果您将其string
转换为,Int32
您应该能够正确评估您的条件。
推荐阅读
- powershell - ForEach 和 $_ 空结果
- html - 覆盖而不使用相对父级和填充子级
- c# - 如何使用 C# 读取 MiCOM 继电器的保持寄存器(ModBus RTU over RS-485 通信)
- mysql - Mysql数据库别名过滤器
- node.js - Dockerfile 和 npm prune --production
- javascript - 当网站在 iPhone 中加载时,预加载器不工作
- sql - 从不同表中提取动态日期范围后计算付款金额
- swift - 从 3d 对象创建 ARRaycastQuery
- docker - 通过 docker 命令运行 cypress 时,cypress type() 未定义
- logging - nftables:如何记录从路由器发出的数据包?