java实现计算“1+3+5+7+…+99”的值。
时间: 2023-09-29 16:07:41 浏览: 116
求 1+3+5+7+……+99 的和 sum.py
要实现计算“1 3 5 7 … 99”的值的Java代码,可以参考以下两个引用的代码片段:
引用中的代码:
```java
public class Task04 {
public static void main(String[] args) {
int sum;
sum = 0;
for (int i = 1; i < 100; i += 2) {
sum = sum + i;
}
System.out.println("1 3 5 … 99 = " + sum);
}
}
```
引用中的代码:
```java
public class task04_1 {
public static void main(String[] args) {
int sum;
sum = 0;
for (int i = 1; i <= 50; i++) {
sum = sum + (2 * i - 1);
}
System.out.println("1 3 5 … 99 = " + sum);
}
}
```
以上两段代码均实现了计算从1到99中奇数的和。你可以根据自己的需求选择其中之一来使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [Java项目案例-判断成绩和计算1+3+5+......+99的值](https://blog.csdn.net/qq_67308195/article/details/124086384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [JAVA 计算1+3+5+……+99的和](https://blog.csdn.net/dmzshyl1123/article/details/125102039)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文