1. 程式人生 > >程式設計菜鳥到大佬之路:C語言程式特別篇(一)

程式設計菜鳥到大佬之路:C語言程式特別篇(一)

程式設計習題

迴圈例題選講

  • 例1.乘方計算
    • 給出一個整數a和一個正整數n,求乘方ana^n
    • 輸入:一行,包含兩個整數a和n。 -1000000 <= a <= 1000000,1 <= n <= 10000。
    • 輸出:一個整數,即乘方結果。題目保證最終結果的絕對值不超過1000000。
    • 樣例輸入:2 3
    • 樣例輸出:8
# include <iostream>
using namespace std;
int main()
{
	int a, n;
	cin >> a >> n;
	int result = a;
	for (int i = 2; i <= n; ++i)
	{
		result = a * result;	
	} 
	cout << result;
	return 0;	
} 
  • 例2. 輸入若干個整數求最大值
    • 輸入若干個整數(可正可負,不超過int的表示範圍),輸出最大值。
    • Sample Input:-100 -20 20 -2
    • Sample Output:20
# include <iostream>
using namespace std;
int main()
{
	int n, max;
	bool first = true;	// 輸入的是否是第一個數
	while (cin >> n)
	{
		if (first)
		{
			max = n;
			first = false;
		}
		else if (n > max)
		{
			max = n
		}
	}
	cout << max << endl;
	return 0;	
} 
  • 例3. 輸入至少2個整數,求最大值和第二大值
    • Sample Input:1 5 6 3 4 6
    • Sample Output:6 6
    • Sample Input:1 5 6 3 4
    • Sample Output:6 5
# include <iostream>
using namespace std;
int main() 
{
	int n,max1,max2;
	int num = 0; // 輸入的是第幾個數
	while(cin >> n) 
	{
		++num;
		if( num == 1)
				max1 = n;
		else if( num == 2)
		{
			if( n > max1) 
			{
				max2 = max1;
				max1 = n;
			}
			else
				max2 = n;
		}
		else 
		{ // num > 2
			if( n >= max1) 
			{
				max2 = max1;
				max1 = n;
			}
			else if( n > max2 )
				max2 = n;
		}
	cout << max1 << " " << max2 << endl;
	return 0;
	}
}
  • 例4. 斐波那契數列
    • 菲波那契數列是指這樣的數列: 數列的第一個和第二個數都為1,接下來每個數都等於前面2個數之和。給出一個正整數k,要求菲波那契數列中第k個數是多少。
    • 輸入:輸入一行,包含一個正整數k。(1 <= k <= 46)
    • 輸出:輸出一行,包含一個正整數,表示菲波那契數列中第k個數的大小
    • 樣例輸入:19
    • 樣例輸出:4181
# include <iostream>
using namespace std;
int main()
{
	int a1 = 1, a2 = 1;
	int k;
	cin >> k;
	if (k == 1 || k == 2)
	{
		cout << 1 << endl;
	}
	else
	{
		int sum;
		for (int i = 3; i <= k; ++i)
		{
			sum = a1 + a2;
			a1 = a2;
			a2 = sum;
		}
		cout << a2 <<endl;
	}
	return 0;
}
  • 例5. 求階乘的和
    • 給定正整數n,求不大於n的正整數的階乘的和(即求1!+2!+3!+…+n!)
    • 輸入:輸入有一行,包含一個正整數n(1 < n < 12)。
    • 輸出:輸出有一行,階乘的和。
    • 樣例輸入:5
    • 樣例輸出:153
# include <iostream>
using namespace std;
int main() 
{
	int n;
	cin >> n;
	int sum = 0;
	int factorial = 1;
	for(int i = 1;i <= n; ++i) 
	{
		factorial *= i;
		sum += factorial;
	}
	cout << sum ;
	return 0;
}
  • 例6. 輸入正整數n(n>=2),求不大於n的全部質數
# include <iostream>
using namespace std;
int main() 
{
	int n;
	cin >> n;
	cout << 1 << endl << 2 << endl;
	for(int i = 3; i <= n; i+=2) 
	{ //每次判斷i是否是質數
		int k;
		for(k = 3; k < i; k+=2) 
		{
			if( i % k == 0)
				break;
			if( k*k > i)
				break;
		}
		if( k*k > i) 
			cout << i << endl;
	}
	return 0;
}