小白入门编程六个练手的有趣的计算问题

1 近似求平方根

6517281-e778efded4698d3a.jpg

2 计算e的值

6517281-b342ce20ecbda567.jpg

3 三角形三边求面积

6517281-8e10c44471ec2906.jpg

4 斐波那契数列的三种算法

6517281-306c66e0a1581665.jpg

5 计算阶乘

6517281-95928d1c76bd8a2b.jpg

6 一元二次方程求解

6517281-fc3a1b3fdd2f7558.jpg

附代码

1 近似求平方根

#include

using namespace std;

int main()

{

const double dif = 0.0000001;

double n;

cin>>n;

double i = 1.0;

double mul = 0.0;

int j = 0;

while(abs(n-mul)>dif)

{

mul = i * i;

i=(i+n/i)/2;

j++;

cout<

}

cout<

cout<

cin.get();cin.get();

return 0;

}

2 计算e的值

#include

#include

int main()

{

double e = 1;

double jc = 1;

int num,i;

printf("利用无穷级数e=1+1/1!+1/2!+1/3!+1/4!+...+1/n!求e,你希望所求的e使用的级数(1-10):");

scanf("%d",&num);

for(i=1;i<=num;i++)

{

jc=jc*i;

e+=1.0/jc;

}

printf("e近似等于:%f",e);

system("pause");

return 0;

}

3 三角形三边求面积

from math import sqrt

a = float(input("Length of edge a:"))

b = float(input("Length of edge b:"))

c = float(input("Length of edge c:"))

if a>0 and b>0 and c>0 and 

a+b>c and b+c>a and a+c>b:

....s=(a+b+c)/2

....area = sqrt(s*(s-a)*(s-b)*(s-c))

....print("Area of the triangle:",area)

else:

....print("three edge:", a, b, c, "cannot form a trangle!")

4 斐波那契数列的三种算法

def fibnc(n):

....a,b=1,1

....for i in range(n-1):

........a,b = b,a+b # 元组赋值

....return a

print(fibnc(11))

def fib(n):

....if n == 1 or n == 2:

........return 1

....return fib(n-1) + fib(n-2)

print(fib(11))

def fibn(n):

....if n == 1:

........return [1]

....if n == 2:

........retunr [1,1]

....fibs = [1,1]

....for i in range(2,n):

........fibs.append(fibs[-1] + fibs[-2])

....return fibs

print(fibn(11))

5 计算阶乘

def main():

....i = eval(input("Enter an int for a Fibonacci number:"))

....print("The Fibonacci number of", i , "is", fib(i))

def fib(i):

....if i == 0:.................... # base case

........return 0

....elif i == 1:....................# base case

........return 1

....else:........................ # redcution and recursive calls

........return fib(i-1) + fib(i-2)

main()............................ # call the main function

6 一元二次方程求解

#include

#include

using namespace std;

int main()

{

double a,b,c,d,x,y;

cout<<"一元二次方程一般式为ax^2+bx+c=0"<

cout<<"请输入系数a,b,c。"<

cin>>a>>b>>c;

cout<<"你输入的方程是"<

d=b*b-4*a*c;

if(d>=0)

{

if(d>0)

{

x=((-b)+sqrt(d))/(2*a);

y=((-b)-sqrt(d))/(2*a); 

cout<<"方程有两个解"<<""<

}

else

{

x=((-b)+sqrt(d))/(2*a);

cout<<"方程有一个的根:"<

}

}

else 

cout<<"这个方程没有实数解"<

cin.get();cin.get();

return 0;

}

猜你喜欢

转载自blog.csdn.net/weixin_34198453/article/details/86828552