java - 使用 while 循环可被 3 整除的第一个偶数 n 的总和
问题描述
前 N 个也能被 3 整除的偶数之和。因此,如果输入是 5,则前 N 个偶数是 0、2、4、6、8。在这 5 个数字中,只有 6 个能被 3 整除,所以输出将是 6。这是我到目前为止所尝试的:
import java.util.Scanner;
public class Exercise1_3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int count=0;
while(count<n){
// I am stuck here
System.out.print(sum+" ");
sum=sum+2;
count++;
}
}
}
input: 5
// (0, 2, 4, 6, 8) only 6 divides by 3 thus
output: 6
解决方案
我发现您的代码有几个问题:
- 你总是在总和上加 2,而不是把能被 3 整除的数字相加。
- 你永远不会检查这个数字是否能被三整除。您可以使用类似的代码进行检查
n % 3 == 0
。
试试这个代码:
import java.util.Scanner;
public class Exercise1_3 {
public static void main(String[] args) {
// Read the input.
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
// Loop over the first n even numbers.
int sum = 0;
int count = 0;
while (count < n) {
int nextEven = 2 * count;
// If the number is divisible by 3, then add to the running sum.
if (nextEven % 3 == 0) {
sum += nextEven;
}
count++;
}
// Print the output.
System.out.println(sum);
}
}
推荐阅读
- sap-cloud-sdk - 如何在 SAP Cloud SDK 中为自己的 OData 服务执行集成测试
- ajax - Ajax 图像上传给我 405 错误(不允许方法)并且来源已被 CORS 策略阻止
- html - 悬停时的 CSS 过渡类宽度
- typescript - TYPEORM 设置 fk 为 1:m / m:1
- vue.js - VueJS 和 NuxtJS 中是否有类似 React Fragment 的东西?
- c# - 使用 UploadFromStreamAsync 上传文件后 Azure Blob 文件已损坏
- laravel - 为什么 laravel 消息包中有两个相同的方法?
- python - Shopify 最新 sdk 版本
- c - 使用 strcpy 到 calloc'ed 位置时,大小为 1 的写入无效
- javascript - React 中的脚本加载问题