如何在随机序列中对一些数字求和?

huangapple go评论125阅读模式
英文:

How to can I sum some numbers in a random series?

问题

我试图创建一个程序,它会生成随机的两位整数,直到产生一个10或20为止。然后计算数字的数量,小于10的数字之和,等于15的数字之和,大于70的数字之和。有人能帮帮我吗?

这是我的代码:

// 变量
int numRandom = 0, less10, equal15, more70;

// 处理
txtS.setText("随机数字: " + "\n");
for (int mountNum = 0; numRandom != 10 && numRandom != 20; mountNum++) {
    numRandom = (int) (Math.random() * 90 + 10);  // 生成10到99之间的随机整数
    txtS.append(numRandom + "\n");
}
英文:

I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:

// Variables
int numRandom = 0, less10, equal15, more70;
	
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
	numRandom = (int) (99 * Math.random());
	txtS.append(numRandom + "\n");
}

答案1

得分: 0

你可以直接存储这些值,并为每种情况创建变量。

这是一个适用于少于10种情况的示例("if语句"将包含在你的for循环内部)。

int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
    sumLessThanTen += numRandom;
    countLessThanTen++;
}
英文:

You could just store the values directly and create variables for each case.

This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).

int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom &lt; 10){
    sumLessThanTen += numRandom;
    countLessThanTen++
}

huangapple
  • 本文由 发表于 2020年7月24日 06:52:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63064249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定