簡體   English   中英

在C#中轉換問題

[英]Converting issue in C#

我不斷收到一條錯誤消息,指出我無法參考第39行將字符串轉換為雙精度型。有人可以查看代碼並讓我知道我要去哪里嗎? 我覺得也許第25行應該為變量“ 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();
        }
    }
}

有兩種編輯方式。

方法1)您應編輯CalculateData函數。 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();
    }

方法2)您應編輯button1_Click函數。 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();
}

希望對您有幫助。

處理用戶輸入(從文本框)時,應使用.TryParse()方法而不是.Parse() 我們不能信任用戶...

另外,如果您輸入的內容可能是實數,那么文化就是一個問題,例如3.4或3,4。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM