简体   繁体   中英

Converting issue in C#

I keep getting an error message stating that I cannot convert a string to a double in reference to line 39. Can someone review the code and let me know where I'm off? I feel that maybe line 25 should list double for the variable "R."

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 Present_Value
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //Declare global variables. 
       /* double F = int.Parse(futureTextBox.Text);
        double R = int.Parse(interestTextBox.Text);
        double N = int.Parse(sitTextBox.Text);*/

        private double CalculateData(int F, int R, int N)
        {
            double P = F/(1 + R)*N;
            return P ;

        }



        private void button1_Click(object sender, EventArgs e)
        {

            int n = int.Parse(sitTextBox.Text);
            int f = int.Parse(futureTextBox.Text);
            int r = double.Parse(intTextBox.Text);

            presentValuelabel.Text = CalculateData(f,r,n).ToString();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            //Close this form.
                this.Close();
        }
    }
}

There are two way to edit.

Method 1) You should edit CalculateData function. int R => double R

private double CalculateData(int F, double R, int N)
{
    double P = F / (1 + R) * N;
    return P;

}
private void button1_Click(object sender, EventArgs e)
    {

        int n = int.Parse(sitTextBox.Text);
        int f = int.Parse(futureTextBox.Text);
        double r = double.Parse(intTextBox.Text);

        presentValuelabel.Text = CalculateData(f, r, n).ToString();
    }

Method 2) You should edit button1_Click function. double.Parse(intTextBox.Text) => int.Parse(intTextBox.Text)

private void button1_Click(object sender, EventArgs e)
{

    int n = int.Parse(sitTextBox.Text);
    int f = int.Parse(futureTextBox.Text);
    int r = int.Parse(intTextBox.Text);

    presentValuelabel.Text = CalculateData(f, r, n).ToString();
}

I hope it will help you.

When dealing with user input (from the textboxes) you should use the .TryParse() methods instead of .Parse() . We cannot trust the users...

Also, if your input might be a real number then culture is an isse, eg 3.4 or 3,4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM