修正以下代码:public class Example{ public static void main(String[] args){ int s = 0 ,e,N,m; int[] a = {1,4,7,13,19,20}; int N = a.length -1; int m = (s+N) /2; Scanner scanner = new Scanner (System.in); int sum = scanner.nextInt(); whlie(s != e){ if(num > a[m]){ s = m; s++; } else if(num < a[m]){ e = m; e--; } m = (e + s) /2; if(num = a[m]){ System.out.println("have"); break; } } } }
时间: 2024-02-10 21:09:39 浏览: 50
修正后的代码如下:
```
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
int s = 0, e, N, m;
int[] a = {1, 4, 7, 13, 19, 20};
N = a.length - 1;
m = (s + N) / 2;
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
e = N;
while (s <= e) {
if (num > a[m]) {
s = m + 1;
} else if (num < a[m]) {
e = m - 1;
} else {
System.out.println("have");
break;
}
m = (s + e) / 2;
}
}
}
```
修正点:
1. 将 `whlie` 改为 `while`。
2. 去掉了重复定义变量 `N` 和 `m`。
3. 初始化变量 `e` 为 `N`。
4. 将 `s != e` 改为 `s <= e`。
5. 在 `if`、`else if` 和 `else` 语句中分别加上了代码块 `{}`。
6. 在 `if (num = a[m])` 中将赋值运算符 `=` 改为相等运算符 `==`。
7. 将 `s++` 和 `e--` 合并为 `s = m + 1` 和 `e = m - 1`。
8. 将求中间位置 `m` 的公式改为 `(s + e) / 2`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)