MIT OCW 6.0001 课程 Problem Set 0

2019-07-24  本文已影响0人  伊甸亚当

参考链接

课程视频
作业链接

Assignment:

Write a program that does the following in order:

  1. Asks the user to enter a number “x”;
  2. Asks the user to enter a number “y”;
  3. Prints out number “x”, raised to the power “y”.
  4. Prints out the log (base 2) of “x”.

Use Spyder to create your program, and save your code in a file named ‘ps0.py’. An example of an interaction with your program is shown below. The words printed in blue are ones the computer should print, based on your commands, while the words in black are an example of a user's input. The colors are simply here to help you distinguish the two components.

Enter number x: 2 
Enter number y: 3 
X**y = 8
log(x) = 1

作业心得

根据提示,本章作业涉及的知识点如下:

程序的实现过程中,遇到几点需要注意的:

  1. input函数返回的是str类型,需要通过int函数转化才能进行运算,否则会报错

TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'"

  1. 一般的数据计算,math库也足够了,numpy提供了更多更方便的函数

程序代码

import math
import numpy

# 因为要参与计算,所以需要使用int函数来转化
x = int(input("Enter number x:"))
y = int(input("Enter number y:"))

# 使用内置函数和math库来实现程序
print("x**y = {}\nlog(x) = {}".format(pow(x, y), int(math.log2(x))))
# 使用numpy库来实现程序
print("x**y = {}\nlog(x) = {}".format(numpy.power(x, y), int(numpy.log2(x))))
上一篇下一篇

猜你喜欢

热点阅读