0

这是我的代码:

var num, totalNum, averageNum, numItems, msg;
msg = "";
totalNum = 0;
numItems = 0;
while(true)
{
   num = get_integer("Please enter a number. Enter -99 to quit.", "type here");
   totalNum += num;
   numItems += 1;
   if (num == -99)
   {
   totalNum += 99;
   msg += "Total is: " +string(totalNum) +"#";
   averageNum = real(totalNum / numItems);
   msg += "Average is: " +string(averageNum);
   show_message(msg);
   break;
   }
}

现在,如果我输入数字 1 和 2,然后输入 -99 来打破循环,我得到的平均值是 1。我想得到实数,而不是整数。有什么帮助吗?

4

5 回答 5

2

2个可能的更正:

...
if (num == -99)
{
totalNum += 99;
numItems -= 1; // <----
msg += "Total is: " +string(totalNum) +"#";
averageNum = real(totalNum) / numItems; // <----
...
于 2009-11-04T05:25:25.357 回答
1

让我们尝试以下方法:

averageNum = real(totalNum / numItems); // to get the real portion of all the result not devide real over integer

或尝试:

averageNum = totalNum / numItems; //immediately , the result may be drivin automatically as a real one.
于 2013-06-07T08:24:22.217 回答
1

不是整数或小数问题。当您输入“-99”退出循环时,numItems 增加 1,导致结果为 (1+2)/3 = 1。您可以使用与固定 totalNum 相同的方法来解决此问题:

         ···
   if (num == -99)
   {
   totalNum += 99;
   numItems -= 1; //Add this to undo the extra count
   msg += "Total is: " +string(totalNum) +"#";
   averageNum = real(totalNum / numItems);
   msg += "Average is: " +string(averageNum);
   show_message(msg);
   break;
   }
}

此外,您可以删除 real()。它在那里毫无用处,因为您正在将真实转换为真实。

于 2012-12-09T16:42:57.533 回答
0

我不知道 GML,但目前,您似乎正在将除法的结果转换为实数,此时为时已晚。

我已经修改了你的程序,做了一些其他的改进。如果它不是有效的 GML,请原谅我。

var num, totalNum, averageNum, numItems, msg;
totalNum = 0;
numItems = 0;
num = get_integer("Please enter a number. Enter -99 to quit.", "type here");
while(num != -99)
{
    totalNum += num;
    numItems += 1;
    num = get_integer("Please enter a number. Enter -99 to quit.", "type here");
}
msg = "Total is: " + string(totalNum) + "#";
averageNum = real(totalNum) / numItems;
msg += "Average is: " + string(averageNum);
show_message(msg);
于 2009-11-04T05:22:20.567 回答
0

我不知道 Game Maker Language 是如何工作的。

但是,尝试替换 averageNum = real(totalNum / numItems);averageNum = real(totalNum) / numItems;

于 2009-11-04T05:22:27.373 回答