2013年4月9日 星期二

[C]Midterm Solutions

#include <stdio.h>
#include <stdlib.h>
void main (void)
{
	//第一題50%
		int a,max,sum=0,n_l_ten=0;
		float avg,n_t=0;
		printf("Enter number a = ");
		scanf("%d",&a);
		if(a > 0)
		{
		max=a;
		sum+=a;
		n_t+=1;
		if(a < 10)
			n_l_ten+=1;
		}
		while(a > 0)
		{
			printf("Enter number a = ");
			scanf("%d",&a);
			if(a > 0)
			{
				sum+=a;
				n_t+=1;
				if(a < 10)
					n_l_ten+=1;
				if(a > max)
					max=a;
			}
		}
		avg=sum/n_t;
		printf("Total %.0f numbers\n",n_t);
		printf("Total %d numbers less than 10\n",n_l_ten);
		printf("Maximum = %d\n",max);
		printf("Average = %.2f\n",avg);
	//顯示季節 20%
		int month;
		printf("Enter the month = ");
		scanf("%d",&month);
		switch(month)
		{
		case 2:
		case 3:
		case 4:
			printf("Now is Spring!\n");
			break;
		case 5:
		case 6:
		case 7:
			printf("Now is Summer!\n");
			break;
		case 8:
		case 9:
		case 10:
			printf("Now is Autumn!\n");
			break;
		case 11:
		case 12:
		case 1:
			printf("Now is Winter!\n");
			break;
		}
	//輾轉相除法 30%
		int n1,n2,gcd,big,temp;
		printf("Enter First number = ");
		scanf("%d",&n1);
		printf("Enter Second number = ");
		scanf("%d",&n2);
		if(n1 > n2)
		{
			big=n2;
			gcd=n1%n2;
		}
		else
		{
			big=n1;
			gcd=n2%n1;
		}
		while(gcd !=0)
		{
			temp=gcd;
			gcd=big%gcd;
			big=temp;
		}
		if(gcd == 0)
			gcd=big;
		printf("gcd (%d,%d) = %d\n",n1,n2,gcd);
	system("pause");
}

以上答案僅供參考,並非唯一解題方法

沒有留言:

張貼留言