C# Progressbar开发问题:三明治掉落模拟如何统计正确面数量并更新进度条
问题根因
- 存储用户输入三明治总数的变量被
odds.Next(2)的返回值直接覆盖,用户输入的数量被完全丢弃,仅执行了1次随机逻辑 - 没有针对每个三明治做循环处理,自然无法统计多份掉落结果,也不会累加调整进度条数值
- 结果输出逻辑仅对应单次随机结果,没有做总数统计
修复代码
基础版本(掉落完成后一次性输出结果)
private void btnStart_Click(object sender, RoutedEventArgs e) { Random odds = new Random(); prgsbrScale.Value = 50; // 单独存储用户输入的总数量,避免覆盖 int totalSandwiches = int.Parse(txtSandwich.Text); int rightCount = 0; int wrongCount = 0; // 循环处理每一个三明治的掉落判定 for (int i = 0; i < totalSandwiches; i++) { int currentResult = odds.Next(2); if (currentResult == 1) { rightCount++; // Math.Clamp用于避免进度条超出0-100的取值范围 prgsbrScale.Value = Math.Clamp(prgsbrScale.Value + 5, 0, 100); } else { wrongCount++; prgsbrScale.Value = Math.Clamp(prgsbrScale.Value - 5, 0, 100); } } // 输出统计结果,需要中文显示可替换为下一行注释内容 txtResultOfAmountOnRightWrongSide.Text = $"Amount on the right side: {rightCount}, Amount on the wrong side: {wrongCount}"; // txtResultOfAmountOnRightWrongSide.Text = $"正确面数量:{rightCount},错误面数量:{wrongCount}"; }
动态效果版本(逐次掉落实时更新进度和统计)
如果需要模拟逐个掉落的动画效果,实时更新界面,可以使用异步实现:
private async void btnStart_Click(object sender, RoutedEventArgs e) { // 点击后禁用按钮避免重复触发 btnStart.IsEnabled = false; Random odds = new Random(); prgsbrScale.Value = 50; int totalSandwiches = int.Parse(txtSandwich.Text); int rightCount = 0; int wrongCount = 0; for (int i = 0; i < totalSandwiches; i++) { int currentResult = odds.Next(2); if (currentResult == 1) { rightCount++; prgsbrScale.Value = Math.Clamp(prgsbrScale.Value + 5, 0, 100); } else { wrongCount++; prgsbrScale.Value = Math.Clamp(prgsbrScale.Value - 5, 0, 100); } // 实时更新统计文本 txtResultOfAmountOnRightWrongSide.Text = $"Amount on the right side: {rightCount}, Amount on the wrong side: {wrongCount}"; // 调整延迟数值可修改掉落动画速度,单位为毫秒 await Task.Delay(100); } btnStart.IsEnabled = true; }
内容的提问来源于stack exchange,提问作者saradvv
相关产品推荐
相关产品推荐

