如何对字符串使用数学运算符? [英] How to use math operators with strings?
问题描述
当用户输入在> = 0到< = 1之间时,我需要在标签上显示某个数字.用户输入是一个字符串,并且我需要将它们之间的数字设置为十进制或双精度.显然,我无法像我一样比较两者,因为运算符无法比较字符串和十进制,双精度或整数.
I need to display a certain number on a label when the user input is between >=0 and <= 1. User input is a string and I need the numbers between to be a decimal or double. Obviously I can't compare the two like I did because the operators can't compare a string and decimal, double, or int.
private void voltageTextBox_TextChanged(object sender, EventArgs e)
{
var RTPower = powerTextBox.Text;
powerTextBox.CharacterCasing = CharacterCasing.Upper;
if (RTPower >= 0 && <= 1)
{
displayLabel4.Text = "1";
}
}
错误:运算符'> ='不能应用于类型为'string'和'int'的操作数
Error: Operator '>=' cannot be applied to operands of type 'string' and 'int'
错误:运算符'< ='不能应用于类型为'string'和'int'的操作数
Error: Operator '<=' cannot be applied to operands of type 'string' and 'int'
如果声明有效,我该如何做?我是否必须将其保留为字符串,在标签中显示,将标签转换为整数然后重新显示?我知道我可以完成这项工作,但这太复杂了.我只需要一个更简单的方法即可.
How can I make that if statement work? Do I have to keep it as a string, display it in label, convert the label to an integer then re-display it? I know I can make that work, but that is far too complicated. I just need an easier way to do this.
推荐答案
int RTPower = Int32.Parse(powerTextBox.Text);
或十进制值
decimal RTPower = Decimal.Parse(powerTextBox.Text);
您需要将值从字符串转换为整数.
You need to convert the value from a string to an int.
此外,我假设您是C#的新手-我的建议是避免使用var并明确声明变量.它将使事情变得更清晰,更容易学习和理解.
Also, I assume you are new to c# - my advice would be to avoid using var and explicitly declare your variables. It will make things clear and easier for you to learn and understand.
这篇关于如何对字符串使用数学运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!