首页 > 解决方案 > 如何编写一个程序,将平均成绩计算为双值,并在消息框中显示成绩?

问题描述

我正在学习成为一名游戏开发人员,我使用 C#。现在其中一项任务如下(从荷兰语翻译而来):

两名学生参加 C# 考试。他们的结果(0 到 100 之间的整数个点)分配给两个变量:

int outcomeStudent1 = 44;
int outcomeStudent2 = 51;

编写一个程序,将平均成绩计算为double- 值并在屏幕上显示该成绩。用计算器检查你的答案。

当我再看几页时,答案就在那里,上面写着:

a、b、c 和 d 的值分别为 5、7、12 和 8

这是我放入 MainWindow.xaml 的内容:

我想要发生的是:

到目前为止,这是我的全部代码(我只从一位同学那里得到了一点帮助,因为她不在她的笔记本电脑旁):

public partial class MainWindow : Window
    {
        int outcomeStudent1 = 44;
        int outcomeStudent2 = 51;

        private void CalculateButton_Click(object sender, RoutedEventArgs e)
        {
            //outcomeStudent1 = 44
            //outcomeStudent2 = 51
            //Write a program that calculates the average grade as a double value

            double variable1;
            double variable2;
            variable1 = 44;
            variable2 = 51;

            int StudentA = 44;
            int StudentB = 51;
            double average;
            average = (double)StudentA + (double)StudentB / 2;

            //2*44=88
            //2*51=102
            //88+102=190
            //190/2=95
            
            MessageBox.Show("Average grade = " + average);
        }
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

我现在迷路了,那我该怎么做才能让这一切发生呢?

标签: c#buttonaverage

解决方案


您需要先从用户界面获取值。为此,您可以访问文本框中的值,如下所示。然后将字符串值转换为整数。

之后用 (x + y) / 2 计算平均值(你的公式是错误的)。然后在消息框中显示结果。

下面的代码应该可以工作。请记住在您的 xaml 文件中创建两个文本框,分别命名为textbox1textbox2(以后可能会考虑更好的命名)

public partial class MainWindow : Window
{
    private void CalculateButton_Click(object sender, RoutedEventArgs e)
    {
        int studentA = Convert.ToInt32(textbox1.Text);
        int studentB = Convert.ToInt32(textbox2.Text);

        double average = (studentA + studentB) / 2.0;
        
        MessageBox.Show("Average grade = " + average);
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

推荐阅读