1、计算Fibonacci数列
/* Displaying Fibonacci sequence up to nth term where n is entered by user. */
#include
int main()
{
int count, n, t1=0, t2=1, display=0;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
count=2; /* count=2 because first two terms are already displayed. */
while (count
结果输出:
Enter number of terms: 10
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+
也可以使用下面的源代码:
/* Displaying Fibonacci series up to certain number entered by user. */
#include
int main()
{
int t1=0, t2=1, display=0, num;
printf("Enter an integer: ");
scanf("%d",&num);
printf("Fibonacci Series: %d+%d+", t1, t2); /* Displaying first two terms */
display=t1+t2;
while(display
结果输出:
Enter an integer: 200
Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89+144+
2、回文检查
源代码:
#include
int main(){
int n,reverse=0,rem,tmp;
printf("Enter a integer:");
scanf("%d",&n);
tmp=n;
while(tmp!=0){
rem=tmp%10;
reverse=reverse*10+rem;
tmp=tmp/10;
}
if(reverse==n){
printf("%d is a palindrome.\n",n);
}else
printf("%d is not a palindrome.\n",n);
return 0;
}
3、质数检查
源代码:
#include
#include
bool judge(int x){
if(x<1) return false;
int bound=(int)sqrt(x)+1;
int i;
for(i=2;i
4、打印金字塔和三角形
源代码:
#include
int main(){
int i,space,rows,k=0;
printf("Enter the number of rows:");
scanf("%d",&rows);
for(i=rows;i>=1;i--){
for(space=1;space<=rows-i;space++){
printf(" ");
}
while(k!=2*i-1){
printf("* ");
k++;
}
k=0;
printf("\n");
}
return 0;
}
5、简单的加减乘除计算器
源代码:
#include
int main(){
char o;
float num1,num2;
printf("Enter the operator +or-or* divide /:\n");
scanf("%c",&o);
scanf("%f%f",&num1,&num2);
switch(o){
case '+':printf("%.1f+%.1f=%.1f\n",num1,num2,num1+num2);break;
case '-':printf("%.1f-%.1f=%.1f\n",num1,num2,num1-num2);break;
case '*':printf("%.1f*%.1f=%.1f\n",num1,num2,num1*num2);break;
case '/':printf("%.1f/%.1f=%.1f\n",num1,num2,num1/num2);break;
default:printf("error!");
break;
}
return 0;
}
6、检查一个数能不能表示成两个质数之和
源代码:
#include
#include
int prime(int x);
int main(){
int n,flag=0,i;
scanf("%d",&n);
for(i=2;i<=n/2;i++){
if(prime(i)!=0){
if(prime(n-i)!=0){
printf("%d=%d+%d\n",n,i,n-i);
flag=1;
}
}
}
if(flag==0)
printf("%d can not be expressed as the sum of two prime number",n);
return 0;
}
int prime(int x){
if(x<=1) return 0;
int bound=(int)sqrt(x)+1;
int i;
for(i=2;i