C#三元运算符重构帕斯卡三角顶点计算结果错误排查
问题说明
完成课程作业时编写的帕斯卡三角计算程序,核心功能为计算并输出三角的顶点值。已注释的旧版代码可正常运行,为锻炼编码能力,尝试使用三元运算符精简重构代码提升整洁度,但重构后出现计算结果异常:测试样例输入4,1,7,9,2时,正确顶点值应为7,新代码运行输出结果为6,需要排查逻辑问题。
完整原代码如下:
using System; namespace Lab4 { class Program { // apex will add each pairs of cards, if over 9 wtvr remaining is thats the new sum static int Pyramid(int x, int y) { x = (x + y > 9) ? (x + y) - 9 : x + y; return x; } static int Apex(int Card1,int Card2,int Card3,int Card4,int Card5) { int x = 0; int cycle = 0; while (cycle < 5 ) // tells it how many cycles it needs to get to the apex { //having a cycle counter allows the if statment to know when to cancel the last card out ,from 5-2 Card1 = (cycle == 5) ? Card1 : Pyramid(Card1, Card2); Card2 = (cycle == 4) ? 0 : Pyramid(Card2, Card3); Card3 = (cycle == 3) ? 0 : Pyramid(Card3, Card4); Card4 = (cycle == 2) ? 0 : Pyramid(Card4, Card5); Card5 = 0; cycle++; } x = Card1; return x; } static int PickCard() //method is used to let user input card and check to see if card is a correct input 1-9 { int x=int.Parse(Console.ReadLine()); //allows user to input their card choice while (x < 1 || x > 9) { Console.WriteLine("Please Only Choose Cards From 1-9"); x = int.Parse(Console.ReadLine()); } Console.WriteLine("Please Choose Next Card"); // tells user to choose next card, works since its after the while loop verifies their og input return x; } static void Main(string[] args) { int ApexCard; int Card1,Card2,Card3, Card4, Card5; Console.WriteLine("Please Choose 5 Cards Going Left To Right From 1-9"); Card1 = PickCard(); Card2 = PickCard(); Card3 = PickCard(); Card4 = PickCard(); Card5 = PickCard(); ApexCard = Apex(Card1, Card2, Card3, Card4, Card5); Console.WriteLine(""); Console.WriteLine($"Your Apex Card is {ApexCard}"); //Author Jonaven Gray 06/21 } } }
问题排查
核心逻辑错误集中在Apex方法的迭代控制部分,共有3处问题:
- 循环次数设置错误
5个初始值逐层计算顶点,每次迭代有效数字长度减1(5→4→3→2→1),仅需要4次迭代即可得到结果。原代码设置while (cycle <5)会多执行1次迭代,用已经得到的顶点值和后置0的无效值重复计算,直接污染结果。 - 无效的边界判断
循环条件为cycle <5,循环体内cycle的取值范围是0-4,永远不会等于5,因此Card1 = (cycle == 5) ? Card1 : Pyramid(Card1, Card2)的判断完全无效,哪怕迭代到只剩1个有效顶点值,还是会拿顶点值和后置0的Card2做计算,得出错误结果。 - 置0时机全部错位
原代码中Card2、Card3、Card4的置0触发cycle值全部晚了1次迭代:
- Card4应该在第2次迭代(cycle=1)后置0,不再参与后续计算,原代码设置为cycle=2才置0
- Card3应该在第3次迭代(cycle=2)后置0,原代码设置为cycle=3才置0
- Card2应该在第4次迭代(cycle=3)后置0,原代码设置为cycle=4才置0
置0时机延后会导致程序拿有效位和已经置0的无效位做求和计算,引入错误值。
修复方案
调整循环次数和置0触发条件即可,修复后的Apex方法代码如下:
static int Apex(int Card1,int Card2,int Card3,int Card4,int Card5) { int cycle = 0; // 5个初始值仅需4次迭代得到顶点 while (cycle < 4) { Card1 = Pyramid(Card1, Card2); Card2 = (cycle == 3) ? 0 : Pyramid(Card2, Card3); Card3 = (cycle == 2) ? 0 : Pyramid(Card3, Card4); Card4 = (cycle == 1) ? 0 : Pyramid(Card4, Card5); Card5 = 0; cycle++; } return Card1; }
使用测试样例4,1,7,9,2验证,修复后代码输出顶点值为7,符合预期。
内容的提问来源于stack exchange,提问作者JGray
相关产品推荐
相关产品推荐

