最簡單的C程式舉例——選擇結構設計
1,輸入兩個實數,按從小到大的順序輸出這兩個數
#include"stdio.h"
int main()
{
float a,b,t;
scanf("%f%f",&a,&b);
if(a>b)
{
t=a;
a=b;
b=t;
}
printf("%4.2f\n%4.2f",a,b);
return 0;
}
輸入內容:
3.6
3.2
運行結果:
3.20
3.60
//同理,判斷三個的輸出順序,
#include"stdio.h"
int main()
{
float a,b,c,t;
scanf("%f%f%f",&a,&b,&c);
if(a>b)
{
t=a;
a=b;
b=t;
}
if(a>c)
{
t=a;
a=c;
c=t;
}
if(b>c)
{
t=b;
b=c;
c=t;
}
printf("%4.2f\n%4.2f\n%4.2f",a,b,c);
return 0;
}
輸入內容:
3.9
3.6
3.7
運行結果:
3.60
3.70
3.90
2,編一程式,輸入一個小于1000的正數,輸出其平方根(平方根不為整數,則輸出其整數部分)
#include"stdio.h"
#include"math.h"
#define m 1000
int main()
{
int i,k;
printf("輸入一個小于%d的整數i:",m);
scanf("%d",&i);
if(i>m)
{
printf("輸入的資料不符合要求,請重新輸入一個小于%d的整數i:",m);
scanf("%d",&i);
}
k=sqrt(i);
printf("%d的平方根的整數部分是%d\n",i,k);
return 0;
}
輸入內容:
輸入一個小于1000的整數i:999
運行結果:
999的平方根的整數部分是31
3,寫程式,輸入x的值,輸出y相應的值
y=x (x<1)
y=2x-1 (1<=x<10)
y=3x-11 (x>=10)
#include"stdio.h"
int main()
{
int x,y;
printf("輸入x的值:");
scanf("%d",&x);
if(x<1)
{
y=x;
printf("x=%d\ny=%d",x,y);
}
else if(x<10)
{
y=2*x-1;
printf("x=%d\ny=%d",x,y);
}
else
{
y=3*x-11;
printf("x=%d\ny=%d",x,y);
}
return 0;
}
輸入內容:
4
運行結果:
x=4
y=7
4,給出一百分制成績,要求輸出成績等級“A,B,C,D,E”.90以上為A,以此類推,60以下為E,
#include"stdio.h"
int main()
{
float score;
char grade;
printf("請輸入學生成績:");
scanf("%f",&score);
while(score>100 || score<0)
{
printf("成績有誤,請重新輸入");
scanf("%f",&score);
}
switch((int)(score/10))
{
case 10:
case 9:grade='A';
break;
case 8:grade='B';
break;
case 7:grade='C';
break;
case 6:grade='D';
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:grade='E';
}
printf("成績是%3.1f,相應等第為%c\n",score,grade);
return 0;
}
輸入內容:
請輸入學生成績:90.5
運行結果:
成績是90.5,相應等第為A
5,給出一個不多于5位的正整數,要求:
1)求出它是幾位數;
2)分別輸出每一位數字;
3)按逆序輸出各位數字;
#include"stdio.h"
#include"math.h"
int main()
{
int num,indiv,ten,hundred,thousand,ten_thousand,place;
printf("請輸入一個整數(0~99999):");
scanf("%d",&num);
if(num>9999)
place=5;
else if(num>999)
place=4;
else if(num>99)
place=3;
else if(num>9)
place=2;
else
place=1;
printf("位數:%d\n",place);
printf("每位數字為:");
ten_thousand=num/10000;
thousand=(int)(num-ten_thousand*10000)/1000;
hundred=(int)(num-ten_thousand*10000-thousand*1000)/100;
ten=(int)(num-ten_thousand*10000-thousand*1000-hundred*100)/10;
indiv=(int)(num-ten_thousand*10000-thousand*1000-hundred*100-ten*10);
switch(place)
{
case 5:
printf("%d,%d,%d,%d,%d\n",ten_thousand,thousand,hundred,ten,indiv);
printf("反序數為:");
printf("%d%d%d%d%d",indiv,ten,hundred,thousand,ten_thousand);
break;
case 4:
printf("%d,%d,%d,%d\n",thousand,hundred,ten,indiv);
printf("反序數為:");
printf("%d%d%d%d",indiv,ten,hundred,thousand);
break;
case 3:
printf("%d,%d,%d\n",hundred,ten,indiv);
printf("反序數為:");
printf("%d%d%d",indiv,ten,hundred);
break;
case 2:
printf("%d,%d\n",ten,indiv);
printf("反序數為:");
printf("%d%d",indiv,ten);
break;
case 1:
printf("%%d\n",indiv);
printf("反序數為:");
printf("%d",indiv);
break;
}
return 0;
}
輸入內容:
請輸入一個整數(0~99999):96584
運行結果:
位數:5
每位數字分別為:9,6,5,8,4
反序數為:48569
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/273264.html
標籤:其他
