习题 3 数字和数学计算

每一种编程语言都包含处理数字和进行数学计算的方法。不必担心,程序员经常撒谎说他们是多么牛的数学天才,其实他们根本不是。如果他们真是数学天才,他们早就去从事数学相关的行业了,而不是写写广告程序和社交网络游戏,从人们身上偷赚点小钱而已。

这章练习里有很多的数学运算符号。我们来看一遍它们都叫什么名字。你要一边写一边念出它们的名字来,直到你念烦了为止。名字如下:

+ plus 加号
- minus 减号
/ slash 斜杠
* asterisk 星号
% percent 百分号
< less-than 小于号
> greater-than 大于号
<= less-than-equal 小于等于号
>= greater-than-equal 大于等于号

有没有注意到以上只是些符号,没有运算操作呢?写完下面的练习代码后,再回到上面的列表,写出每个符号的作用。例如 + 是用来做加法运算的。

print ("I will now count my chickens:") #输出纯文本

print ("Hens", 25 + 30 / 6) #输出

print ("Roosters", 100 - 25 * 3 % 4)

print ("Now I will count the eggs:")

print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)

print ("Is it true that 3 + 2 < 5 - 7?")

print (3 + 2 < 5 - 7)

print ("What is 3 + 2?", 3 + 2)
print ("What is 5 - 7?", 5 - 7)

print ("Oh, that's why it's False.")

print ("How about some more.")

print ("Is it greater?", 5 > -2)
print ("Is it greater or equal?", 5 >= -2)
print ("Is it less or equal?", 5 <= -2)

I will now count my chickens:
Hens 30.0
Roosters 97
Now I will count the eggs:
6.75
Is it true that 3 + 2 < 5 - 7?
False
What is 3 + 2? 5
What is 5 - 7? -2
Oh, that's why it's False.
How about some more.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False

加分习题

1.使用 # 在代码每一行的前一行为自己写一个注解,说明一下这一行的作用。

2.记得开始时的 <练习 0> 吧?用里边的方法把 Python 运行起来,然后使用刚才学到的运算符号,把Python当做计算器玩玩。

3.自己找个想要计算的东西,写一个 .py 文件把它计算出来。

print (250*2+38-17.8686)

print("250*2+38-17.8686")

250*2+38-17.8686

520.1314
250*2+38-17.8686
520.1314

4.有没有发现计算结果是”错”的呢?计算结果只有整数,没有小数部分。研究一下这是为什么,搜索一下“浮点数(floating point number)”是什么东西。

print (75/4)
print (75.0/4)
print (75/4.0)
print (75.0/4.0)
print (75.000/4.000)

18.75
18.75
18.75
18.75
18.75

5.使用浮点数重写一遍 ex3.py,让它的计算结果更准确(提示: 20.0 是一个浮点数)。

猜你喜欢

转载自www.cnblogs.com/lshnice/p/9251262.html