最近正在复习C语言,感觉一元二次方程这个程序在C语言里还是很有代表性的,所以总结一下:
在流程控制当中,for循环与while循环的用法完全等价,至于到底用谁,完全靠感觉,而do…while这个循环基本上很少用,主要用于人机交互,接下来用一元二次方程为例:
实例程序:
# include <stdio.h>
# include <math.h>
int main(void)
{
double a,b,c;
double delta;
double x1,x2;
char ch;
do
{
printf("请从键盘上输入a,b,c的数值:\n");
scanf("%lf %lf %lf",&a,&b,&c);
delta = b*b - 4*a*c;
if (delta > 0)
{
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
printf("x1与x2的数值是:%lf %lf\n",x1,x2);
}
else if (delta == 0)
{
x1 = (-b + sqrt(delta))/(2*a);
x2 = x1;
printf("x1与x2的数值是:%lf %lf\n",x1,x2);
}
else
printf("x1与x2的数值无解!\n");
printf("您还想继续吗?继续请输入Y or y : \n");
scanf(" %c",&ch); //注意:%c前面有空格
}while( ch=='Y' || ch == 'y');
return 0;
}
运行结果:
当然,我们也可以用函数进行模块化:
实例程序:
# include <stdio.h>
# include <math.h>
void compute(double a, double b, double delta)
{
double x1;
double x2;
if ( b > 0 )
{
x1 = (-b + sqrt(delta))/2*a;
x2 = (-b - sqrt(delta))/2*a;
printf("x1的数值是:%lf ,x2的数值是:%lf",x1,x2);
}
else if ( b == 0)
{
x1 = (-b + sqrt(delta))/2*a;
x2 = x1;
printf("x1的数值是:%lf ,x2的数值是:%lf",x1,x2);
}
if ( b < 0)
{
printf("x1与x2的数值为空值!");
}
}
int main()
{
double a,b,c;
double delta;
printf("从键盘上输入相应的数值:\n");
scanf("%lf %lf %lf",&a,&b,&c);
delta = b*b - 4*a*c;
compute(a, b, delta);
return 0;
}
运行结果:
如果用Java语言的话,我们可以这么写:
import java.util.Scanner;
public class App1 //在Java当中函数的基本单位是类
{
public static void main(String[] args)
{
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
double delta;
delta = b*b - 4*a*c;
compute(a, b, delta);
}
public static void compute(double a, double b, double delta)
{
double x1;
double x2;
if ( b > 0 )
{
x1 = (-b + Math.sqrt(delta))/2*a;
x2 = (-b - Math.sqrt(delta))/2*a;
System.out.println("x1的数值是:"+x1+"\t"+"x2的数值是:"+"\t"+x2);
}
else if ( b == 0)
{
x1 = (-b + Math.sqrt(delta))/2*a;
x2 = x1;
System.out.println("x1的数值是:"+x1+"\t"+"x2的数值是:"+"\t"+x2);
}
if ( b < 0)
{
System.out.println("x1与x2的数值为空值!");
}
}
}
运行结果:
1 5 6
x1的数值是:-2.0 x2的数值是: -3.0
python版本:
#!/usr/bin/python
# -*- coding:utf-8 -*-
"""
python实现一元二次方程.
"""
import cmath
def compute_func(a,b,c,delta):
"""
:param a:
:param b:
:param c:
:param delta:
:return: 返回相应的运算结果.
"""
x1,x2 = '无解','无解'
if delta > 0:
x1 = (-b + cmath.sqrt(delta)) / 2*a
x2 = (-b - cmath.sqrt(delta)) / 2*a
elif delta == 0:
x1 = x2 = (-b) / 2*a
else:
pass
return x1,x2
print("请从键盘上输入ax2+bx+c=0相应的参数数值:")
a = float(input("请输入参数a的数值:"))
b = float(input("请输入参数b的数值:"))
c = float(input("请输入参数c的数值:"))
delta = b*b - 4*a*c;
x1,x2 = compute_func(a,b,c,delta)
print(x1,x2)