创建一个for循环以使之前的值翻倍
问题描述:
我目前正在学习Java,我有一个任务,要求我编写for循环。我需要创建一个允许用户输入的小程序,然后使用for循环将消息告诉用户他们的信息。我需要for循环来允许,总结用户投入的天数,以及他们每天的谷物数量,同时我还需要每天获得两倍的谷物数量。创建一个for循环以使之前的值翻倍
实施例:
第1天你得到1粒米,总共1个晶粒
日的2你得到2个晶粒大米的总共3粒
3你日大米共计7粒
4日的4粒你得到8粒米,共15粒
X天的你米X谷物的TOT Y晶粒
我不完全确定如何设置我的for循环来做到这一点。这是我到目前为止。
public static void GrainCounter()
{
Scanner s = new Scanner(System.in);
System.out.println("How many days worth of grain do you have?");
int days = s.nextInt();
int sum = 0;
for (int i = 0; i <= days; i++)
{
sum = sum + i;
}
System.out.print("Day " + days + " you got " + sum + " grains of rice");
}
答
的公式实际上是,
Day X you get 2**X grains of rice for a total of Y grains
你sum
应该1
开始,你应该把你print
在循环(也想要打印i
为天)。喜欢的东西,
System.out.println("Day 1 you get 1 grain of rice for a total of 1 grain");
int sum = 1;
for (int i = 1; i <= days; i++)
{
sum += Math.pow(2, i);
System.out.println("Day " + (i + 1) + " you got " + (int)Math.pow(2,i) +
" grains of rice for a total of " + sum + " grains");
}
你也可以写println
作为
System.out.printf("Day %d you got %d grains of rice for a total of %d grains%n",
i + 1, (int) Math.pow(2, i), sum);
答
所有你需要做的是初始化rice
与1
,只是不断增加它本身在for
-loop,直到你的循环迭代int i
达到天数-1(因为您初始化为1,所以不需要额外的迭代)
public static int doubleDays(int days) {
int rice = 1;
for (int i = 0; i < days - 1; i++) {
rice += rice;
}
return rice;
}
答
试试这个:
import java.util.Scanner;
public class GrainCounter{
public static void main(String[] agrs){
Scanner in = new Scanner(System.in);
System.out.println("How Many Days Worth Of Grain Do You Have?");
int days = in.nextInt();
int sum =1, dailySum=1;
System.out.println("Day 1 you get 1 grain of rice for a total of 1 grain");
for (int i =1; i <days; i++){
dailySum*=2;
sum +=dailySum;
System.out.print("Day "+ (i+1) + " you get " + dailySum
+ " grain of rice for a total of "
+ sum + " grain\n");
}
}
}
结果将是10天:
How Many Days Worth Of Grain Do You Have?
10
Day 1 you get 1 grain of rice for a total of 1 grain
Day 2 you get 2 grain of rice for a total of 3 grain
Day 3 you get 4 grain of rice for a total of 7 grain
Day 4 you get 8 grain of rice for a total of 15 grain
Day 5 you get 16 grain of rice for a total of 31 grain
Day 6 you get 32 grain of rice for a total of 63 grain
Day 7 you get 64 grain of rice for a total of 127 grain
Day 8 you get 128 grain of rice for a total of 255 grain
Day 9 you get 256 grain of rice for a total of 511 grain
Day 10 you get 512 grain of rice for a total of 1023 grain
答
问题是你的代码试图使用一天作为变量,但实际上您的变量实际上是前几天的获得。
public static void GrainCounter(){
Scanner s = new Scanner(System.in);
System.out.println("How many days worth of grain do you have?");
int days = s.nextInt();
int sum = 1;
previousDay = 1;
for (int i = 2; i <= days; i++){
sum += previousDay*2;
previousDay = previousDay*2;
}
System.out.print("Day " + days + " you got " + sum + " grains of rice");
}
请按照一个简单的Java教程,它会清楚地指出它,加上一堆其他*有用的东西。 – rotgers
请在这里添加ypur代码而不是图片。 – Moon
'sum + = 1 shmosel