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

1 近似求平方根

2 计算e的值

3 三角形三边求面积

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

5 计算阶乘

6 一元二次方程求解

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

{

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

cout

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;

}

－End－

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20190121A0DZJ900?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-01-26

2021-01-26

2021-01-26

2021-01-26

2021-01-26

2021-01-26