1. 程式人生 > >C語言程式碼比較18ba/16

C語言程式碼比較18ba/16

the kata:
題目描述:

In a small town the population is p0 = 1000 at the beginning of a
year. The population regularly increases by 2 percent per year and
moreover 50 new inhabitants per year come to live in the town. How
many years does the town need to see its population greater or equal
to p = 1200 inhabitants?

More generally given parameters:

p0, percent, aug (inhabitants coming or leaving each year), p (population to surpass)

the function nb_year should return n number of entire years needed to
get a population greater or equal to p.
aug is an integer, percent a positive or null number, p0 and p are positive integers (> 0)

我的程式1
Growth of a population;

在這裡插入圖片描述遞迴代替迴圈:
在這裡插入圖片描述

一個簡單的遞迴
出口條件的p0>=p,
不符合則renturn 0+1;
再不符合則return 0+1+1;

大佬的程式:
在這裡插入圖片描述

ratio 比例
static inline int function();
static 是宣告一個靜態變數,作用範圍是一個traslation unit,或稱一個編譯單元,就是一個原始碼包括include ,macro…
inline 指顯式提示編譯器在呼叫函式時不要進行一般的呼叫,而是將函式的body程式碼加到呼叫處,差不多是include 的意思。

但從written differently:後的>= 這個符號就沒看懂了。

但是出現了對數學公式的運用,看起來很nb

另一題:

details:
Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b.
Note: a and b are not ordered!

我的程式,簡單的交換值,累加:
在這裡插入圖片描述

進一步可以運用三目運算子來代替if:
在這裡插入圖片描述

最好的程式:
在這裡插入圖片描述

先是用異或代替宣告新變數來交換值
再用求和公式來代替累加

介紹一下按位異或:
原理是 1:滿足交換律
2.與自身異或得0
3.與0異或得自身

a = a^b;
b = a^b = a ^ b ^ b=a(把a= a^b代入)