第七章 用函数实现模块化程序设计
2.二元一次方程
#include<stdio.h>
#include<math.h>
float two(float x,float y,float z)
{
float x1=0;
float x2=0;
x1=(-y+sqrt(z))/(2*x);
x2=(-y-sqrt(z))/(2*x);
printf("%3.2f\n%3.2f",x1,x2);
return 0;
}
float one(float x,float y,float z)
{
float x1=0;
x1=(-y+sqrt(z))/(2*x);
printf("%3.2f",x1);
return 0;
}
float no()
{
printf("no");
return 0;
}
int main()
{
float a,b,c;
a=b=c=0;
float d=0;
scanf("%f%f%f",&a,&b,&c);
d=b*b-4*a*c;
if(d>0) two(a,b,d);
else if(d=0) one(a,b,d);
else no();
return 0;
}
3.输入一个数,判断素数
#include<stdio.h>
bool sushu(int a)
{
int leap=0;
bool result=1;
for(int i=2;i<=a/2;i++)
if(a%i==0)
leap++;
if(leap==0) result=1;
else result=0;
return(result);
}
int main()
{
int x=0;
scanf("%d",&x);
bool c=sushu(x);
if(c==1) printf("yes");
else printf("no");
return 0;
}
4.二维数组行列置换
#include<stdio.h>
void change(int x[3][3])
{
for(int i=1;i<=2;i++)
for(int j=0;j<=1;j++)
{
int temp=x[i][j];
x[i][j]=x[j][i];
x[j][i]=temp;
}
for(i=0;i<3;i++)
{
for(int j=0;j<3;j++)
printf("%d",x[i][j]);
printf("\n");
}
}
int main()
{
int a[3][3]={0};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
scanf("%d",&a[i][j]);
change(a);
return 0;
}
5.字符串反向存放
#include<iostream>
#include<string>
using namespace std;
char change(char x[])
{
int end=0;
int i=0;
int j=0;
end=strlen(x);
for(j=end-1,i=0;i<end/2;i++,j--)
{
char temp=x[i];
x[i]=x[j];
x[j]=temp;
}
return(*x);
}
int main()
{
char a[30]={'a'};
gets(a);
change(a);
puts(a);
return 0;
}