Reputation: 1
For school, I have to create a calculator where you enter the radius of a circle and it calculates the circumference and the area.
I tried coding it and everything I tried just won't work. It kept giving me errors along the lines of it having difficulty converting the textbox into a double, and other errors. This is my code:
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 Circumference
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtCircumference = Math.PI * Math.Pow(txtRadius, 2);
txtArea = 2 * Math.PI * txtRadius;
}
}
}
I'm used to coding with python so C# is kinda out of my comfort zone.
Upvotes: 0
Views: 709
Reputation: 1041
You may be new to C# but the most glaring issue is with WinForm controls. My answer assumes that txtRadius
, txtCircumference
, and txtArea
are all TextBox
controls.
Note I am writing this freeform and not in a VS editor so I may have errors.
private void btnCalculate_Click(object sender, EventArgs e)
{
if (!double.TryParse(txtRadius.Text, out double radius))
{
throw new Exception("Radius is a not a valid double.");
}
txtCircumference.Text = (Math.PI * radius * radius).ToString();
txtArea.Text = (2.0 * Math.PI * radius).ToString();
}
Observe that each TextBox
has a .Text
string property. For me to interchange a double with a string requires me to parse the string into a double, or else use ToString() to write the double as a string.
Upvotes: 2