2017-05-30 49 views
-9

直到一分钱加倍,每天将在JavaScript和Python $ 10,000美元多少天?请给出一个简单的例子,计算

var count = 0 
for (var i=0; i<10000; i++) { 
    count += 1 
} 

上面的代码是我正在寻找的响应。我是初学者,发现了解简单的解决方案有时有助于解决更大的问题。

+3

所以,如果你发布的代码是你正在寻找的代码,什么是你的问题对我们? –

+0

这段代码已经够简单了。 – doutriforce

+2

从技术上说,你并没有将循环中的值加倍,尝试从'count = 1'开始,然后在循环中使用'count * = 2'(而不是每次加1,每次乘以2) –

回答

1

这是有问题的Python中的解决方案。

pennies = 1 
days = 0 
while (pennies < 10000*100) : 
    pennies *= 2 
    days += 1 
print (days , 'days to reach 10000') 
+2

错误!你有一分钱(0.01美元),需要赚取10000美元 –

+0

你对不起我的错。我不知道有关便士。 –

1
var pennies_total = 1 // total amount of pennies 
var days_total = 1 // days past 
var pennies = 1  // doubled amount for the current day 

while (pennies_total < 10000*100) { 
    pennies *= 2    // doubling pennies for current day 
    pennies_total += pennies // adding the doubled pennies to the total 
    days_total += 1   // increasing the days count 
} 

print days_total 
+1

是python还是javascript。我想你已经混淆了两者;) –

0

我不明白,如果这是一个问题,或不按你说的“上面的代码是我要寻找的响应”。因为这段代码并没有回答这个问题:“在Javascript和Python中,每天增加一美分的费用是多少美元?”我承认是的。

pennies = 1 
days = 0 

while ((pennies/100) < 10000): 

    pennies *= 2 
    days += 1 
0

如果您要问如何找到将数值加倍到10,000的花费多少倍,那么您想要改变循环条件以及循环中的操作。

var count = 1; // Start at 1 because we "have 1 penny" already 
var i; // Define an index in this scope to keep track of times doubled 
for (i=0; count < 10000; i++) { // Check that the penny count is less than 10,000... not the number of iterations 
    count *= 2; // Multiply the current value of count by 2 
} 
console.log(i); // Print # times that the penny was doubled 
console.log(count); // Print the value of count (it might not be 10,000 exactly) 

如果你想要一个更加高效和准确的解决方案,你可以随时执行基本2对数:

Math.log2(10000); // 13.287712376549449 

并得到一个整数,只是Math.ceil()它(因为在技术上,如果你去了 - 即使只有一小部分 - 你需要再增加一倍才能达到这个值)。

Math.ceil(Math.log2(10000)); // 14 

最后,如果你只是在寻找数,它需要14天才能有至少10,000便士