如何对字符串使用数学运算符?
How to use math operators with strings?
当用户输入介于 >=0 和 <= 1 之间时,我需要在标签上显示某个数字。用户输入是一个字符串,我需要介于两者之间的数字是小数或双精度。显然我不能像以前那样比较两者,因为运算符不能比较字符串和小数、双精度或整数。
private void voltageTextBox_TextChanged(object sender, EventArgs e)
{
var RTPower = powerTextBox.Text;
powerTextBox.CharacterCasing = CharacterCasing.Upper;
if (RTPower >= 0 && <= 1)
{
displayLabel4.Text = "1";
}
}
Error: Operator '>=' cannot be applied to operands of type 'string' and 'int'
Error: Operator '<=' cannot be applied to operands of type 'string' and 'int'
如何使 if 语句起作用?我是否必须将其保留为字符串,在标签中显示,将标签转换为整数然后重新显示?我知道我可以做到这一点,但这太复杂了。我只需要一种更简单的方法来做到这一点。
你可以像这样转换成int
int x = Int32.Parse(RTPower);
然后你可以比较x。
但是,如果您知道用户输入将在 [0, 9] 之间,那么您可以使用
if(RTPower >= "0" && <= "1")
因为字符串是按字典顺序比较的,所以“1”在“9”之下,而“10”在“2”之下。
第一种方法要好得多,因为它适用于所有数字用户输入
int RTPower = Int32.Parse(powerTextBox.Text);
或十进制值
decimal RTPower = Decimal.Parse(powerTextBox.Text);
您需要将值从字符串转换为整数。
此外,我假设您是 c# 的新手 - 我的建议是避免使用 var 并显式声明您的变量。它会让你学习和理解的东西更清晰、更容易。
当用户输入介于 >=0 和 <= 1 之间时,我需要在标签上显示某个数字。用户输入是一个字符串,我需要介于两者之间的数字是小数或双精度。显然我不能像以前那样比较两者,因为运算符不能比较字符串和小数、双精度或整数。
private void voltageTextBox_TextChanged(object sender, EventArgs e)
{
var RTPower = powerTextBox.Text;
powerTextBox.CharacterCasing = CharacterCasing.Upper;
if (RTPower >= 0 && <= 1)
{
displayLabel4.Text = "1";
}
}
Error: Operator '>=' cannot be applied to operands of type 'string' and 'int'
Error: Operator '<=' cannot be applied to operands of type 'string' and 'int'
如何使 if 语句起作用?我是否必须将其保留为字符串,在标签中显示,将标签转换为整数然后重新显示?我知道我可以做到这一点,但这太复杂了。我只需要一种更简单的方法来做到这一点。
你可以像这样转换成int
int x = Int32.Parse(RTPower);
然后你可以比较x。
但是,如果您知道用户输入将在 [0, 9] 之间,那么您可以使用
if(RTPower >= "0" && <= "1")
因为字符串是按字典顺序比较的,所以“1”在“9”之下,而“10”在“2”之下。
第一种方法要好得多,因为它适用于所有数字用户输入
int RTPower = Int32.Parse(powerTextBox.Text);
或十进制值
decimal RTPower = Decimal.Parse(powerTextBox.Text);
您需要将值从字符串转换为整数。
此外,我假设您是 c# 的新手 - 我的建议是避免使用 var 并显式声明您的变量。它会让你学习和理解的东西更清晰、更容易。