开发者

Game Maker Language calculating proper average

Here is my code:

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;
   }
}

Right now, if I enter the number 开发者_运维百科1 and 2 and then -99 to break the loop, I get an average of 1. I want to get the real number, not the integer. Any help?


2 possible corrections:

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


let's try the following:

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

or try :

averageNum = totalNum / numItems; //immediately , the result may be drivin automatically as a real one.


Is not an integer or decimal problem. When you enter "-99" to exit the loop, numItems increases by 1, causing the result to be (1+2)/3 = 1. You could fix this the same way you fixed 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;
   }
}

Also, you can remove real(). It serves no purpose there cause you're converting a real to a real.


I don't know how Game Maker Language works.

However, try replacing averageNum = real(totalNum / numItems); with averageNum = real(totalNum) / numItems;


I don't know GML but at the moment, you seem to be converting the result of the division to a real, and by this time it is too late.

I have revised your program, making some other improvements. Forgive me if it's not valid 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜