人手不足/三元运算符如果统计不起作用,逻辑在我看来是正确的,所以我需要另一双眼睛来检查它



所以我为我的课程创建的程序是pascals三角形,该方法取三角形的顶点并显示它。被注释掉的旧代码rn确实有效,没有任何问题,但由于我想尝试并始终提高我的编码技能,我试着用简短的if语句使它更干净、更小,如果你看到我的问题是什么,我很感激你让我知道,获得正确顶点的样本数据是4,1,7,9,2 = Apex(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
}
}
}

使用当前逻辑进行的顶点计算不正确。

你的旧逻辑是(评论和工作):

static int Apex(int Card1,int Card2,int Card3,int Card4,int Card5)
{
int x = 0;
int cycle = 0;
while (cycle < 5 )
{
Card1 = Pyramid(Card1, Card2);
Card2 = Pyramid(Card2, Card3);
Card3 = Pyramid(Card3, Card4);
Card4 = Pyramid(Card4, Card5);
Card5 = (cycle == 1) ? Card5 = 0 : Card5=0;

cycle++;

if (cycle==1) 
{            
Card5 = 0;
}
else if (cycle == 2)
{
Card4 = 0;
}
else if (cycle == 3)
{
Card3 = 0;
}
else if (cycle == 4)
{
Card2 = 0;
}
else if (cycle == 5)
{
x=Card1;
}
}
x = Card1;
return x;
}

所以你调用卡片的CCD_ 3方法;重置";卡到CCD_ 4。

您当前的代码做的是不同的事情——您首先检查cycle,然后在满足条件的情况下调用Pyramid(请注意,在以前的版本中,您总是调用Pyramid)。所以Apex方法应该是这样的:

static int Apex(int Card1,int Card2,int Card3,int Card4,int Card5)
{
int x = 0;
int cycle = 0;
while (cycle < 5 )
{
Card1 = Pyramid(Card1, Card2);
Card2 = Pyramid(Card2, Card3);
Card3 = Pyramid(Card3, Card4);
Card4 = Pyramid(Card4, Card5);          

cycle++;

Card2 = (cycle == 4) ? 0 : Card2;
Card3 = (cycle == 3) ? 0 : Card3;
Card4 = (cycle == 2) ? 0 : Card4;
Card5 = (cycle == 1) ? 0 : Card5;
}
x = Card1;
return x;
}

Pyramid方法是正确的(ternaryif-else版本)。

最新更新