【问题标题】:Program ignoring if-statements during while-loops程序在 while 循环期间忽略 if 语句
【发布时间】:2021-05-31 09:58:33
【问题描述】:

我正在编写一个 python 程序,它使用给定的方程更新坐标:(x,y) = (ax-by, ay+bx)。这应该为每个步骤(n)完成,其中包括c+1 数量的微步骤。所以基本上对于这 4 个步骤中的每一个,我都会更新位置 3 次。

import math
import os
import random
import re
import sys

#
# Complete the 'findPosition' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
#  1. INTEGER s
#  2. INTEGER x0
#  3. INTEGER y0
#  4. INTEGER a
#  5. INTEGER b
#  6. INTEGER c
#  7. INTEGER l
#  8. INTEGER n
#

def findPosition(s, x0, y0, a, b, c, l, n):
    # Write your code here
    xf = yf = 0
    t = 0
    while (n > 0):
        while (t <= c):
            xf = (a * x0) - (b * y0)
            yf = (a * y0) + (b * x0)
            if (xf >= s):
                xf = xf - s
            if (yf >= s):
                yf = yf - s
            if (xf < 0):
                xf = xf + s
            if (yf < 0):
                yf = yf + s
            x0 = xf
            y0 = yf
            #print (xf, yf)
            t = t + 1
        t = 0
        n = n - 1
    return (xf, yf)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    first_multiple_input = input().rstrip().split()
    a = int(first_multiple_input[0])
    b = int(first_multiple_input[1])
    c = int(first_multiple_input[2])
    l = int(first_multiple_input[3])
 
    second_multiple_input = input().rstrip().split()
    s = int(second_multiple_input[0])
    x0 = int(second_multiple_input[1])
    y0 = int(second_multiple_input[2])
    n = int(second_multiple_input[3])
 
    result = findPosition(s, x0, y0, a, b, c, l, n)

    fptr.write(' '.join(map(str, result)))
    fptr.write('\n')
    fptr.close()

问题是我的代码在程序中的某个时间(在步骤 3 的微步骤 1 期间)忽略了我的 if 语句。 我应该得到的输出是:

(4, 7)  (1, 18) (7 ,14)
(0, 12) (11, 1) (21, 13)
(6, 1)  (11, 8) (14, 4)
(1, 22) (3, 22) (7, 1)

我实际得到的是:

(4, 7)  (1, 18)  (7, 14)
(0, 12)  (11, 1)  (21, 13)
(6, 24)  (11, 31)  (14, 50)
(1, 91)  (-66, 160)  (-269, 231)

这是用于输入:a=2b=1c=2l=1s=23x0=3y0=2n=4

【问题讨论】:

    标签: python python-3.x if-statement while-loop


    【解决方案1】:

    它不会忽略您的if 语句。您的 if 声明并不能反映您的需求。在第 6 步中,xf,yf 变为 (29,47)。 47 > 23,所以你减去 23 得到 24。你不允许 xf 或 yf 大于 TWICE 的情况。您想要的是模运算符,如下所示。哦,请注意,在 Python 中,ifwhilereturn 语句不需要括号。

    def findPosition(s, x0, y0, a, b, c, l, n):
        for i in range(n):
            for t in range(c+1):
                xf = ((a * x0) - (b * y0)) % s
                yf = ((a * y0) + (b * x0)) % s
                x0 = xf
                y0 = yf
                print (i, t, c, s, xf, yf)
        return xf, yf
    
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 2019-10-22
    • 1970-01-01
    • 2013-06-09
    • 2014-01-21
    • 2015-11-08
    相关资源
    最近更新 更多