CS50 Lab 1: Population Growth

👀 1 min read 👀

大家好,我是 Cindy,最近跟同事小夥伴相約一起看 CS50 的課程,CS50 (Introduction to Computer Science)是一堂美國哈佛大學知名的通識課程,完全免費,在 edxyoutubeCS50-Study-Group github 都可以非常容易地看到。

這篇文章是我練習寫 Week 1 的作業(因為不知道要放在哪裡,才不會以後找不到,所以就決定放在部落格啦),歡迎大家有更好的解法可以一起討論唷~

題目:Lab 1: Population Growth

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <cs50.h>
#include <stdio.h>

int main(void)
{
// Prompt for start size
int start_size;
do
{
start_size = get_int("Start size: ");
}
while (start_size < 9);

// Prompt for end size
int end_size;
do
{
end_size = get_int("End size: ");
}
while (end_size < start_size);

// Calculate number of years until we reach threshold
// Big O(1)
int year = (int) floor(log( (double)end_size/ (double)start_size) / log(13.0/12.0));

// Big O(n)
// int year = 0;
// do
// {
// start_size = start_size + start_size/3 - start_size/4;
// year += 1;
// }
// while (start_size < end_size);

// Print number of years
printf("Years: %i\n", year);
}