简体   繁体   English

为什么WinForms中的textBox无法显示双倍?

[英]Why textBox in WinForms cant display double?

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 P2_7_24_2016_ED_app
{
    public partial class Form1 : Form
    {
        int win;
        int loss;
        int winCounter;
        int lossCounter;
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonWin_Click(object sender, EventArgs e)
        {
            this.textBoxWin.Text = "";
            ++win;
            ++winCounter;
            this.textBoxWin.Text = win.ToString();
        }

        private void buttonLoss_Click(object sender, EventArgs e)
        {
            this.textBoxLoss.Text = "";
            ++loss;
            ++lossCounter;
            this.textBoxLoss.Text = loss.ToString();
        }

        private void buttonRate_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            double result = winCounter / (winCounter + lossCounter);
            textBox1.Text = result.ToString();
        }
    }
}

This is the code in windows form application, its short so i'm not going to explain everything. 这是Windows窗体应用程序中的代码,它很简短,所以我将不解释所有内容。 Problem is that in the end textBox1.Text = result.ToString(); 问题在于,最终textBox1.Text = result.ToString(); is showing "0", but it should be some numbers. 显示“ 0”,但应该是一些数字。 When the win winCounter is like 1, and lossCounter is 1 it should insert 1/(1+1) = 0.5 but it says "0". 当win winCounter类似于1,而lossCounter为1时,应插入1 /(1 + 1)= 0.5,但显示为“ 0”。 I tried everything i knew so please give me a tip. 我尝试了我所知道的一切,所以请给我小费。

This is integer arithmetic: 这是整数运算:

(winCounter/(winCounter+lossCounter))

The result is not going to be what you expect. 结果将不会达到您的期望。

Cast either winCounter or (winCounter+lossCounter) to a floating point type (float, double or decimal depending on the speed/accuracy you need) before doing the division: winCounter ,将winCounter(winCounter+lossCounter)转换为浮点类型(浮点,双精度或十进制,具体取决于您所需的速度/精度):

 (winCounter/(decimal)(winCounter+lossCounter))

or 要么

 ((double)winCounter/(winCounter+lossCounter))

and you'll get the result you expect. 您将获得预期的结果。

As described in the comments, you will need to cast your result. 如评论中所述,您将需要cast结果。 This should work: 这应该工作:

textBox1.Text = (winCounter/(double)(winCounter+lossCounter)).ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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