PDA

View Full Version : Share viết chương trình tim UCLN,rut gon phan so, dem so tu va so dong



dayto.kdh
08-14-2011, 10:27 AM
/*CT tim ucln,rut gon phan so, dem so tu va so dong*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>


int a,b; ;
int menu();
//bai 1: tim ucln
int tim_uoc(int a,int b);
void ucln();
//bai 2: rut gon phan so
int ucln(int a, int b);
void rutgonphanso();
//bai 3: dem so tu va so dong
int sotu(char st[]);
void demsotuvadong();


void main()
{
int chon, don=0;
do
{
chon=menu();
switch(chon)
{
case 1: ucln();
break;
case 2: rutgonphanso();
break;
case 3: demsotuvadong();
break;
case 4: exit(0);
break;
case 0: don=1;
}
}
while(!don);
}
int menu()
{
clrscr();
int c;


printf("\n\n ++++++=====MENU CHUONG TRINH====++++");
printf("\n\n 1.tim uoc chung lon nhat \n\n");
printf("\n\n 2. rut gon phan so\n\n");
printf("\n\n 3. dem so tu va dem so dong\n\n");
printf("\n\n CHON CHUC NANG TUONG UNG\n\n");
do
{
scanf("%d", &c);
}
while(c<1||c>4);
return c;
}




//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
// bai1: tim culn
void ucln()
{
int a,b;
clrscr();
printf("\n nhap a:");
scanf(" %d",&a);
printf("\n nhap b:");
scanf("%b",&b);
printf("\n ucln cua %d va %d la %d",a,b,ucln(a,b));
getch();
}
int tim_uoc(int a, int b)
{
if(a==0||b==0)
return 0;
else
while(a!=b)
if(a>b)
a=a-b;
else
b=b-a;
return a;
}
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//bai 2: rut gon phan so
void rutgonphanso()
{
int tu,mau,tam;
clrscr();
printf("\n nhap tu:");
scanf("%d",&tu);
printf("\n nhap mau:");
scanf("%d",&mau);
printf("\n phan so vua nhap la %d/%d", tu,mau);
if(mau==0)
printf(" phan so khong co nghia");
else
if(tu==0)
printf("\n phan so sau khi rut gon la:%d/%d,tu,mau");
else
{
tam=ucln(tu,mau);
tu=tu/tam;
mau=mau/tam;
printf("\n phan so sau khi rut gon la %d/%d,tu,mau");
}
getch();
}
int ucln(int a, int b)
{
if(a==0||b==0)
return 0;
else
while (a!=b)
if (a>b)
a=a-b;
else
b=b-a;
return a;
}


//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// bai 3: dem so tu va so dong
int sotu(char st[]);
void demsotuvadong()
{
int demtu=0,demdong=0;
char st[25];
FILE*f;
clrscr();
f=fopen("d:\bai1.inp","r");
if(f==NULL)
{
printf("\n khong the mo file!");
exit(0);
}
else
{
do
{
fgets(st,255,f);
demdong++;
demtu+=sotu(st);
}
while(!feof(f));
fclose(f);
}
f=fopen("d:\bai1.out","wt");
if(f==NULL)
printf("\n khong the mo file!");
exit(0);
}
else
{
fprintf(f,"%d\n",demtu);
fprintf(f,"%d\n",demdong);
fclose(f);
printf("\n so tu dem duocla: %d",demtu);
printf("\n so dong dem duoc la: %d", demdong);
}
getch();
}
int sotu(char st[])
{
int dai,demtu=0;
dai=strlen(st);


if(st[0]!='')
demtu++ ;
for(int i=1;i<=dai;i++)
if((st[i]!='')&&(st[i+1]==''))
demtu++;
return demtu;
}




Bài này mình viết có gì sai sót mong các bạn trao đổi nhé