游戏制作者语言计算适当的平均值

时间:2009-11-04 05:16:55

标签: scripting game-maker

这是我的代码:

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.我想得到实数,而不是整数。有什么帮助吗?

5 个答案:

答案 0 :(得分:2)

2个可能的更正:

...
if (num == -99)
{
totalNum += 99;
numItems -= 1; // <----
msg += "Total is: " +string(totalNum) +"#";
averageNum = real(totalNum) / numItems; // <----
...

答案 1 :(得分: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.

答案 2 :(得分: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);

答案 3 :(得分:0)

我不知道Game Maker语言的工作原理。

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

。{

答案 4 :(得分:0)

不是整数或小数问题。 当您输入“-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()。它没有任何意义,因为你将真实转化为真实。