编辑为了清晰.我为混乱而道歉:3
好吧,所以我正在关注一个在线CS课程,我们应该用C语言编写一个程序,它会告诉你如果你在月初有一分钱并且加倍一分钱你会有多少钱每天.
每天你会得到你昨天的两倍加上前几天的一切.
示例:您从.01开始,以及在第3天计算运行总计的内容.因此第一天是.01,第二天是.02,第三天是.04.在第3天,你将有0.01 + 0.02 + 0.04(.09).
该计划打算在任何给定月份(28-31天)的持续时间内计算此过程.
我正在努力实现这一点.我已经把它翻了一倍,但我不确定如何将之前计算的日子放在一起.
这是我的代码:
#include <stdio.h>
#include <math.h>
int main(void) {
/*days represents total days in months*/
/*pens represents the number of pennies on the first day*/
long long days;
long long pens;
do {
printf("Enter the number of days in the month: ");
scanf("%llu", &days);
} while(days < 28 || days > 31);
printf("Enter the initial number of pennies: ");
scanf("%llu", &pens);
for (int i=0; i<= days-1; i++) {
pens += pow(2,i);
printf("You'll have $%llu\n", pens);
}
}
Run Code Online (Sandbox Code Playgroud)
edit2:好的,所以我想我已经修好了,这要归功于你所有的精彩建议.我把最后一部分改为:
for (int i=0; i<= days-1; i++)
{
pens = pens + (pens * 2);
}
total = pens / 100;
printf("You'll have $%.2f\n", total);
}
Run Code Online (Sandbox Code Playgroud)
虽然输出仍然存在轻微问题(我想,这是由于我正在使用的数据类型?)它打印出来:
你有$ 0.00你有$ 0.00你有$ 0.00你有$ 0.00你有$ 2.00你有$ 7.00你有$ 21.00你有$ 65.00你有$ 196.00你有$ 590.00你有$ 1771.00你有$ 5314.00你有$ 15943.00你有$ 47829.00你有$ 143489.00你有$ 430467.00你有$ 1291401.00你有$ 3874204.00
等等
非常好,但我认为它不是那么准确,因为前几次迭代是0.00.
好吧,让我们将你要做的事转化为伪代码:
var daily_amount = 0.01
var total = daily_amount
iteration_over_days:
daily_amount *= 2
total += daily_amount
Run Code Online (Sandbox Code Playgroud)
从那里,你需要做的就是翻译成C.
请享用!
long您也可以从1开始,然后在结尾除以100:$ 0.01 - > $ 1,而不是使用数据类型