c# - 如何编写一个程序,将平均成绩计算为双值,并在消息框中显示成绩?
问题描述
我正在学习成为一名游戏开发人员,我使用 C#。现在其中一项任务如下(从荷兰语翻译而来):
两名学生参加 C# 考试。他们的结果(0 到 100 之间的整数个点)分配给两个变量:
int outcomeStudent1 = 44; int outcomeStudent2 = 51;
编写一个程序,将平均成绩计算为
double
- 值并在屏幕上显示该成绩。用计算器检查你的答案。
当我再看几页时,答案就在那里,上面写着:
a、b、c 和 d 的值分别为 5、7、12 和 8
这是我放入 MainWindow.xaml 的内容:
- 两个带有内容的标签:
- 结果学生 1
- 结果学生 2
- 两个文本框(已在属性中命名),因此我可以在其中输入这些值
- 内容为计算成绩的按钮
我想要发生的是:
- 我在文本框中输入两个值,当我单击按钮时,我希望该消息框显示平均成绩
到目前为止,这是我的全部代码(我只从一位同学那里得到了一点帮助,因为她不在她的笔记本电脑旁):
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();
}
}
}
我现在迷路了,那我该怎么做才能让这一切发生呢?
解决方案
您需要先从用户界面获取值。为此,您可以访问文本框中的值,如下所示。然后将字符串值转换为整数。
之后用 (x + y) / 2 计算平均值(你的公式是错误的)。然后在消息框中显示结果。
下面的代码应该可以工作。请记住在您的 xaml 文件中创建两个文本框,分别命名为textbox1
和textbox2
(以后可能会考虑更好的命名)
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();
}
}
推荐阅读
- reactjs - 如何使用 setInterval 每秒增加一个 React 状态?
- python - 如何向 Tkinter Matplotlib 导航工具栏添加“编辑”选项?
- azure-eventgrid - Azure 事件网格创建订阅:“无权执行操作”
- javascript - 为什么 vue 子组件上的方法被调用两次
- html - 在css中画一条垂直虚线
- php - Composer包安装时有需求冲突,但没有需求
- flutter - NoSuchMethodError:在 null 上调用了 getter 'photoUrl'?
- python - python程序执行后如何运行外部程序
- apache-spark - pyspark 将多列转换为不同的数据类型
- excel - 在 VA02 表格控件中读取文本