无法将类型'double'隐式转换为'string' [英] Cannot implicity convert type 'double' to 'string'
问题描述
我正在编写一个程序,以获取一个圆的半径并输出直径,面积和周长.我试图从直径开始,但我不断收到错误:无法将类型'double'隐式转换为'string'.我已经使用整数完成了类似的程序,但是我无法弄清楚我的一生,即如何在文本框中接收浮点数并计算它们,以便可以输出它们.到目前为止,这是我的代码.
I am making a program to take the radius of a circle and output the diameter, area, and circumference. I'm trying to start with the diameter, but I keep receiving the error: Cannot implicitly convert type 'double' to 'string.' I've done similar programs using integers, but I can't figure out for the life of me, how to receive floats in text boxes and calculate them so I can output them. This is my code so far.
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
double pi = 3.14159;
lblDiameter.Text = (double.Parse(radius.Text)) * (double.Parse(radius.Text));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Circles</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox
id="radius"
Runat="server" />
<br />
<asp:Button
id="Button1"
Text="Calculate"
OnClick="Button1_Click"
Runat="server" />
<asp:Label
id="lblDiameter"
Runat="server" />
</div>
</form>
</body>
</html>
我要去哪里错了?
推荐答案
您可能只是缺少.ToString():
You're probably just missing a .ToString():
lblDiameter.Text = (double.Parse(radius.Text) * double.Parse(radius.Text)).ToString();
这会更清楚,您可以通过将数字存储在局部变量中来避免对字符串进行两次解析:
It'd be clearer and you'd avoid parsing the string twice by storing the number in a local variable:
var value = double.Parse(radius.Text);
lblDiameter.Text = (value * value).ToString();
现在,直径真的等于半径的平方吗?;)
Now, is a diameter really equal to the square of the radius? ;)
这篇关于无法将类型'double'隐式转换为'string'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!