1. 程式人生 > >C語言經典案例(4~~6)

C語言經典案例(4~~6)

(4) 題目:判斷101-200之間有多少個素數,並輸出所有素數。

/* Note:Your choice is C IDE */
#include "stdio.h"
 main()

{
     int  i,x, y,n,flag;
  i=0;
   for ( x=101; x<=200; x++)   
   {flag = 1;

     
      for (y=2;y<x; y++)  
      {
        if ( x%y==0) 
          { flag = 0;
             break;}
          
    }
if (  flag ==1)
        { printf("%10d", x);
          i=i+1;} 
   }
printf("\n");
   printf("共有%d個質數",i);}

執行結果

(5) 題目:輸出九九乘法表

/* Note:Your choice is C IDE */
#include "stdio.h"
void main()
{
    int i,j;
    for(i=1;i<=9;i++)
    {for(j=1;j<=i;j++)
    {
    printf("%d*%d=%-5d",j,i,j*i);    
    }
    printf("\n");
    }

執行結果

(6)題目:輸入三個整數x,y,z,請把這三個數由小到大輸出。

/* Note:Your choice is C IDE */
#include "stdio.h"
void main()
{  
    int t,x,y,z;
    printf("請輸入三個整數\n");
   scanf("%d %d %d",&x,&y,&z);
   if(x>y)
   {
       t=x;
       x=y;
       y=t;
   } 
    if(x>z)
   {
       t=x;
       x=z;
       z=t;
       }
   if(y>z)
   {
       t=y;
       y=z;
       z=t;       
   }
  printf("從小到大排列:%d %d %d",x,y,z);

}

執行結果