轉載自:https://blog.csdn.net/xia0liang/article/details/53157455
【程序14】
題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。
1.程序分析:對n進行分解質因數,應先找到一個最小的質數k,然後按下述步驟完成:
(1)如果這個質數恰等於n,則說明分解質因數的過程已經結束,打印出即可。
(2)如果n〈〉k,但n能被k整除,則應打印出k的值,並用n除以k的商,作爲新的正整數你n,重複執行第一步。
(3)如果n不能被k整除,則用k+1作爲k的值,重複執行第一步。
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int n, i;
scanf("%d", &n);
printf("n=");
for (i = 2; i <= n; i++)
{
while (n != i)
{
if (n%i == 0)
{
printf("%d*", i);
n = n / i;
}
else
break;
}
}
printf("%d", n);
system("pause");
}
【程序15】
題目:利用條件運算符的嵌套來完成此題:學習成績〉=90分的同學用A表示,60-89分之間的用B表示,60分以下的用C表示。
1.程序分析:(a〉b)?a:b這是條件運算符的基本例子。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int score;
char grade;
printf("please input a score\n");
scanf("%d", &score);
grade = score >= 90 ? 'A' : (score >= 60 ? 'B' : 'C');
printf("%d belongs to %c", score,grade);
system("pause");
}
【程序16】
題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。
1.程序分析:利用輾除法。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int a, b, num1, num2, temp;
printf("please input two numbers:\n");
scanf("%d,%d",&num1,&num2);
if (num1 < num2)
{
temp = num1;
num1 = num2;
num2 = temp;
}
a = num1; b = num2;
while (b != 0)
{
temp = a%b;
a = b;
b = temp;
}
printf("公約數:%d\n", a);
printf("公倍數:%d\n", num1*num2 / a);
system("pause");
}
【程序17】
題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
1.程序分析:利用while語句,條件爲輸入的字符不爲’\n’.
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
char c;
int letters = 0, space = 0, digit = 0, others = 0;
printf("please input some characters\n");
while ((c = getchar()) != '\n')
{
if (c >= 'a'&&c <= 'z' || c >= 'A'&&c <= 'Z')
letters++;
else if (c == ' ')
space++;
else if (c >= '0'&&c <= '9')
digit++;
else
others++;
}
printf("輸入的字符串中letters=%d space=%d digit=%d others=%d\n", letters, space, digit, others);
system("pause");
}
【程序18】
題目:求s=a+aa+aaa+aaaa+aa...a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加有鍵盤控制。
1.程序分析:關鍵是計算出每一項的值。
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int a, n, count = 1;
long int sn = 0, tn = 0;
printf("please input a and n\n");
scanf("%d,%d", &a, &n);
printf("a=%d,n=%d\n", a, n);
while (count <= n)
{
tn = tn + a;
sn = sn + tn;
a = a * 10;
count++;
}
printf("a+aa+…=%ld\n", sn);
system("pause");
}
【程序19】
題目:一個數如果恰好等於它的因子之和,這個數就稱爲“完數”。例如6=1+2+3.編程找出1000以內的所有完數。
1. 程序分析:請參照程序14.(與原作者的編程不同)
2.程序源代碼:
#include "stdio.h"
#include "stdlib.h"
//#include <windows.h>
int main()
{
//SetConsoleOutputCP(437);
int i, j, sum;
for (i = 2; i <= 1000; i++)
{
sum = 0;
for (j = 1; j<i; j++)
{
if (i%j == 0)
{
sum += j;
}
}
if (sum == i)
printf("It's a Perfect n:%d\n", i);
}
system("pause");
}