我的卡片查找器遇到了逻辑问题,卡了几天
Posted
技术标签:
【中文标题】我的卡片查找器遇到了逻辑问题,卡了几天【英文标题】:I've ran into a logical problem with my card finder, been stuck for some days 【发布时间】:2021-06-23 12:53:28 【问题描述】:我是 javascript 和一般编程的新手。我做了一些简单的项目,现在我正在研究卡片查找器。用户输入他们有多少张卡,然后输入他们还有多少张卡,系统显示丢失的一张。 (例如,我总共有 5 张牌。我剩下的牌是 1、2、4、5。缺少的牌是 3)。在用户插入剩余的卡(最后一张)之前一切正常,然后它会提醒一个非常大的负数或正数。
// Declaring the variables required to find the missing card
var amountOfCards, numOfCards, result, cards, missingCard, remainingCards, resultOfMissingCard;
// Assigning result and cards variables
result = 0;
cards = 1;
// Asking the user how many cards they have
amountOfCards = prompt('How many cards do you have?');
// Changing the number of cards or numOfCards to an integer
numOfCards = parseInt(amountOfCards);
// Finding the missing card equation
missingCard = (amountOfCards*(amountOfCards+1))/2;
// While loop
while (cards < numOfCards)
remainingCards = prompt('What card do you have remaining?') // This line is for the user to enter their remaining cards
cards = parseInt(remainingCards);
result = result + parseInt(remainingCards);
cards++;
// Finding the missing card
resultOfMissingCard = result - missingCard;
// Alerting the user of their missing card
alert('Your missing card is ' + resultOfMissingCard);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./findingthemissingcard.js"></script></body>
</html>
如果你能帮助我,我很感激你们。再说一次,我不是专业人士。真的很新。我认为有问题:
resultOfMissingCard = 结果 - missingCard
【问题讨论】:
【参考方案1】:这样试试吧。
var amountOfCards, numOfCards, result, cards, missingCard, remainingCards, resultOfMissingCard;
result = 0;
cards = 1;
amountOfCards = prompt('How many cards do you have?');
numOfCards = parseInt(amountOfCards);
missingCard = (numOfCards*(numOfCards+1))/2;
while (cards <= numOfCards)
remainingCards = prompt('What card do you have remaining?')
cards = parseInt(remainingCards);
result = result + parseInt(remainingCards);
cards++;
resultOfMissingCard = missingCard - result;
alert('Your missing card is ' + resultOfMissingCard);
您忘记使用 numOfCards
,它是从等式中的字符串转换的 int 来查找丢失的卡片,而不是使用用户输入的实际字符串。而且在while循环中你必须比较cards <= numOfCards
。最后你只需要从missingCard中减去结果。
【讨论】:
【参考方案2】:即使您已经得到答案,我在计算上也有所改进,并且可以按任意顺序输入您仍然拥有的卡片。如您所见,该脚本也短得多。
var stillgot = [], real = 0, cards = prompt("how many cards did you have")
for (var i = 0; i < cards - 1; i++)
stillgot.push(parseInt(prompt("Enter a card you still have")))
var expected = (parseInt(cards)*(parseInt(cards)+1))/2
for(var i = 0; i < stillgot.length; i++)
real = (real + parseInt(stillgot[i]))
var res = (expected - real)
alert("You are missing card " + res)
【讨论】:
以上是关于我的卡片查找器遇到了逻辑问题,卡了几天的主要内容,如果未能解决你的问题,请参考以下文章
我30块买了一个月VPN,卖家说免流量的,我怎么玩了几天我自己本地流量2