java实现100以内加减法
时间: 2023-06-05 21:07:44 浏览: 261
非常简单,您可以使用以下代码实现100以内的加减法运算:
```
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int a = random.nextInt(100);
int b = random.nextInt(100);
int operator = random.nextInt(2);
String op = "";
int result = 0;
if (operator == 0) {
op = "+";
result = a + b;
} else if (operator == 1) {
op = "-";
result = a - b;
}
System.out.println(a + op + b + "=" + result);
}
}
```
这段代码会随机生成两个在0-99范围内的整数,然后随机选择加法或减法运算,并输出运算结果。
相关问题
java用20以内加减法
以下是Java代码,使用20以内的加减法:
```java
import java.util.Random;
public class AdditionSubtractionWithin20 {
public static void main(String[] args) {
Random random = new Random();
int num1, num2, result;
char operator;
for (int i = 0; i < 10; i++) {
num1 = random.nextInt(20) + 1;
num2 = random.nextInt(20) + 1;
operator = random.nextBoolean() ? '+' : '-';
if (operator == '+') {
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
} else {
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
}
}
}
}
```
输出结果:
```
1 + 20 = 21
19 - 17 = 2
11 + 2 = 13
13 + 1 = 14
17 - 1 = 16
3 - 2 = 1
20 - 19 = 1
1 + 9 = 10
11 - 5 = 6
1 - 1 = 0
```
java 二进制加法实现10000以内
下面是Java代码实现10000以内的二进制加法:
```java
public class BinaryAddition {
public static void main(String[] args) {
int num1 = 100;
int num2 = 200;
int sum = num1 + num2;
String binary = Integer.toBinaryString(sum);
// 补足 0,使二进制表示长度为 16
while (binary.length() < 16) {
binary = "0" + binary;
}
System.out.println("二进制表示:" + binary);
}
}
```
在上面的代码中,我们首先定义了两个整数 `num1` 和 `num2`,然后将它们相加得到 `sum`。接着,我们使用 `Integer.toBinaryString()` 方法将 `sum` 转换为二进制字符串。最后,我们使用一个循环来补足 0,使二进制表示长度为16位。最终,我们输出二进制表示。