C#窗体程序编写一个绘图程序,要求随机产生 10 个成绩,生成散点图并统计优良率、合格率与不合格率。
时间: 2024-04-01 19:32:34 浏览: 11
好的,这是一个比较复杂的问题,需要分几个步骤来完成。
首先,我们需要在窗体中添加一个按钮和一个画布控件,用于生成散点图和展示统计结果。
然后,在按钮的点击事件中,我们可以使用 Random 类来随机生成 10 个成绩,并将这些成绩绘制到画布上。代码如下:
```csharp
private void button1_Click(object sender, EventArgs e)
{
Random random = new Random();
int[] scores = new int[10];
for (int i = 0; i < 10; i++)
{
scores[i] = random.Next(0, 101);
int x = i * 30 + 30; // 计算点的横坐标
int y = this.canvas.Height - scores[i]; // 计算点的纵坐标(因为坐标轴的原点在左上角)
this.canvas.CreateGraphics().DrawEllipse(Pens.Blue, x, y, 5, 5); // 绘制点
}
}
```
接下来,我们需要统计优良率、合格率和不合格率。我们可以定义三个变量用于统计,然后遍历成绩数组,根据不同的成绩范围进行累加。代码如下:
```csharp
int excellentCount = 0; // 优秀数
int goodCount = 0; // 良好数
int passCount = 0; // 合格数
int failCount = 0; // 不合格数
for (int i = 0; i < 10; i++)
{
if (scores[i] >= 90)
{
excellentCount++;
}
else if (scores[i] >= 80)
{
goodCount++;
}
else if (scores[i] >= 60)
{
passCount++;
}
else
{
failCount++;
}
}
```
最后,我们将统计结果展示在窗体上。我们可以使用 Label 控件来显示每个等级的人数和比例。代码如下:
```csharp
int totalCount = excellentCount + goodCount + passCount + failCount; // 总人数
this.excellentLabel.Text = "优秀:" + excellentCount + "(" + (excellentCount * 100.0 / totalCount).ToString("0.00") + "%)";
this.goodLabel.Text = "良好:" + goodCount + "(" + (goodCount * 100.0 / totalCount).ToString("0.00") + "%)";
this.passLabel.Text = "合格:" + passCount + "(" + (passCount * 100.0 / totalCount).ToString("0.00") + "%)";
this.failLabel.Text = "不合格:" + failCount + "(" + (failCount * 100.0 / totalCount).ToString("0.00") + "%)";
```
最终的窗体界面可能会像这样:
![绘图程序界面](https://img-blog.csdnimg.cn/20211205180952779.png)
完整的代码如下: