循環結構實驗
C語言設計實驗報告
實驗項目:循環結構實驗
姓名:杜鵬 實驗地點:一教524 實驗時間:5.6
一、實驗目的與要求
1、熟練的掌握for,while,dowhile循環結構。
2、對for,while循環的嵌套加以練習。
二、實驗內容
實驗一
1不知如何使用conio.h的使用
2)實驗代碼
5.3.1 #include<stdio.h>
#include<conio.h>
main()
{
int n,k,s=0;
printf("請輸入一個整數:");
scanf("%d",&n);
for(k=1;k<=n;k++)
{
s=s+k;
printf("%d\t",s);
}
}
3)問題分析
發現在有無#include conio.h的情況下,兩種結果是一樣的。
實驗二
1對于while里面的條件語句的不清晰。不知如何下手。
2)實驗代碼
5.3.2 #include<stdio.h>
#include<conio.h>
main()
{
float x,max,min;
printf("Please input scores:");
scanf("%f",&x);
max=min=x;
while(x>0)
{
if(x>max) max=x;
if(x<min) min=x;
scanf("%f",&x);
}
printf("\nmax=%.2f\nmin=%.2f\n",max,min);
}
3)問題分析
首先就應該判定在while語句中x是否大于0,然后在分別比較。
實驗三
1未能在運算時把n轉化為浮點型
2)實驗代碼
5.3.3 #include<stdio.h>
main()
{
float sum,value;
int n;
printf("請輸入value:");
scanf("%f",&value);
sum=0.0;
n=0;
do{
++n;
sum+=1.0/(float)n;
}
while(sum<value);
printf("n=%d",n);
}
3)問題分析
首先我們要知道do while循環是先執行語句后判斷條件的的。
實驗四
1對于gerchar的認知不夠,以及在for循環中的while內的條件不知是什么。
2)實驗代碼
5.3.4 #include<stdio.h>
main()
{
char c;
int k,data;
data=0;
for(k=0;k<4;k++)
{
while(k<4)
{
c=getchar();
if(c>='0' && c<='9')
break;
}
if(k==0)
data+=(c-'0')*1000;
if(k==1)
data+=(c-'0')*100;
if(k==2)
data+=(c-'0')*10;
if(k==3)
data+=(c-'0');
}
printf("Data=%d ",data);
}
3)問題分析
getchar就是從鍵盤上獲取一個字符,然后判斷這個字符是否是大于'0'小于'9'然后就根據下面的條件運算得到結果。
實驗五
1for循環的嵌套問題,主要是看是否需要大括號
2)實驗代碼
5.3.5 #include<stdio.h>
main()
{
int m,n,k,s;
printf("各種馱法如下:\n");
for(m=1;m*3<=100;m++)
for(n=1;n*2<100;n++)
for(k=1;k/2<=100;k++)
if((3*m+2*n+k/2)==100 && (m+n+k)==100 && (k%2==0))
printf("大馬%3d匹;中馬%3d匹;小馬%3d匹。\n",m,n,k);
}
3)問題分析
對于條件可能會弄錯,以及對于小馬是否是偶數上需要確定。即k%2==0
實驗六
199乘法表的代碼,主要就是注意他的行和列的需求來進行解答
2)實驗代碼
99乘法表 #include<stdio.h>
main()
{
int a,b,c;
for(a=1;a<=9;a++)
{
for(b=1;b<=a;b++)
printf("%d ",a*b);
printf("\n");
}
}
3)問題分析
n行只有n列,所以在內循環當中就要考慮到變量的條件范圍。
實驗七
1對于counter的使用不夠熟練,以及對counter的理解不夠深。
2)實驗代碼
5.4.1 #include<stdio.h>
main()
{
int i,j,counter=0;
i=11;
for(;i<100;i+=2)
{
for(j=2;j<=i-1;j++)
if(i%j==0)
break;
if(counter%10==0)
printf("\n");
if(j>=i)
{
printf("%6d",i);
counter++;
}
}
}
3)問題分析
counter%10指的是每輸入10個數換行。
三、實驗小結
1、對于循環語句的掌握程度自己還是有所欠缺。應該多多訓練,能夠快速的上手。
2、對于循環語句中的條件的使用上,尤其是在嵌套語句中
浙公網安備 33010602011771號