英文:
The program is fine, but if no errors are found, it cannot be executed
问题
这是我写的程序。我在pycharm中测试了它。程序没有问题,但无法执行。
主要功能是输入年份(AD),然后程序可以输出世纪。
#for
#year=1905,year=1700
#1=<year=<2005
#solution(year)=20
#solution(year)=17
我找不到错误。这是Python。
```python
def solution(year):
century=math.ceil(year/100)
if year%100==0:
century-=1
return century
century=solution(year)
print(solution(year))
英文:
This is the program I wrote. I tested it in pycharm. There is nothing wrong with the program, but it cannot be executed.
The main function is to input AD, and the program can output century.
#for
#year=1905,year=1700
#1=<year=<2005
#solution(year)=20
#solution(year)=17
I cannot find the errors. It's Python.
def solution(year):
century=math.ceil(year/100)
if year%100==0:
century-=1
return century
century=solution(year)
print(solution(year))
答案1
得分: 2
首先,在Python中,文本缩进非常重要(制表符)。
为了使您的代码工作,您需要:
- 导入math库(包含
floor()
函数的库定义) - 添加缩进
- 在变量被定义的地方使用它们
工作的代码:
import math
def solution(year):
century=math.floor(year/100)
if year%100!=0:
century+=1
return century
print(solution(1920))
解释:
在第4行,我们检查取模运算的结果。如果结果为0,我们将世纪增加1。然后我们返回世纪的值。如果year % 100等于0,我们不增加century变量的值。
您还需要理解变量的作用域。Year在solution函数中定义为参数。在函数外部无法访问它。
在这些行中:
century=solution(year)
print(solution(year))
您需要明确指定年份。您还可以定义附加变量year
并为其分配值。因此,这将是完全不同于solution()
函数内定义的year
变量。如果您想进一步了解此主题,请搜索“变量屏蔽”。
英文:
First of all, in python text indentation is very important (tabulators).
To make your code work, you need
- import math (library which contains definition for
floor()
function) - add an indentation
- use variables where they are defined
Working code:
import math
def solution(year):
century=math.floor(year/100)
if year%100!=0:
century+=1
return century
print(solution(1920))
Explanation:
in 4th line, we are checking the modulo operation output. If its 0, we increase the century by 1. Then we return the value of century. If year % 100 equals 0, we don't increase value of century variable.
You also need to understand the scope of variables. Year is defined as parameter in solution function. Its not accessible outside of it.
In those lines:
century=solution(year)
print(solution(year))
You need to specify the year explicitly. You can also define additional variable year
and assign value to it. Therefore, this will be totally different variable than year
defined inside the solution()
function. If you want to read further about this topic, search for "variable shadowing".
答案2
得分: 0
import math
def solution(year):
century=math.ceil(year/100)
if year%100==0:
century-=1
return century
测试年份为2000
year = 2000
century=solution(year )
print(century)
英文:
import math
def solution(year):
century=math.ceil(year/100)
if year%100==0:
century-=1
return century
test for year 2000
year = 2000
century=solution(year )
print(century)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论