我正在创建一个具有硬编码数字的简单猜谜游戏。当用户在文本框中输入一个数字并单击该按钮时,如果该数字太低,则背景将变为蓝色并说“太低”。如果数字太高,背景将变为红色并说“太高”。最后,如果猜对了,那么背景会变成绿色并说“那是正确的!”
我觉得答案就在我面前,但我似乎无法弄清楚是否正确。我很确定我必须在第43和46行进行某种转换吗?
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace A12_02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Hardcoded number.
int SecNum = 75;
//Users input.
int Guess = Convert.ToInt32(textBox1.Text);
//Users input was too low.
if (Convert.ToInt32(Guess) < SecNum)
this.BackColor = Color.Blue;
if (Convert.ToInt32(Guess) < SecNum)
OutputText.Text = "Too low.";
//Users input was too high.
if (Convert.ToInt32(Guess) > SecNum)
this.BackColor = Color.Red;
if (Convert.ToInt32(Guess) > SecNum)
OutputText.Text = "Too high.";
//Users input was correct.
if (Guess = SecNum)
this.BackColor = Color.Green;
if (Guess = SecNum)
OutputText.Text = "That's correct!";
}
}
}
答案 0 :(得分:2)
if (Guess == SecNum)
this.BackColor = Color.Green;
我猜你错误地分配了价值,它应该像上面一样。
答案 1 :(得分:2)
问题是单个=
是一项任务。在比较相等性时,您需要使用==
。此外,您无需重复检查相同的条件。您的代码可以缩写为somehwat:
private void button1_Click(object sender, EventArgs e) {
//Hardcoded number.
int SecNum = 75;
//Users input.
int Guess = Convert.ToInt32(textBox1.Text);
if (Guess < SecNum) {
this.BackColor = Color.Blue;
OutputText.Text = "Too low.";
} else if (Guess > SecNum) {
this.BackColor = Color.Red;
OutputText.Text = "Too high.";
} else {
this.BackColor = Color.Green;
OutputText.Text = "That's correct!";
}
}