尝试将WORKING python程序转换为C ++,但无法正常工作?

时间:2019-02-05 05:35:10

标签: python c++

我正在尝试创建一个程序,该程序计算由函数N ^ 2 + N + 41 = y的N个项生成的素数的确切数目

我已经用python完美地编写了程序,并且按预期工作。我也精通C ++语法,并尝试用C ++重新创建相同的程序,但是它所做的事情与我想要的完全不同。我已经在下面发布了.py代码和.cpp代码。希望有人能弄清楚为什么C ++版本无法正常工作。

据我所知,我已经正确转换了我的代码,但是我一生无法确定哪里出了问题。

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2 "
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        />
    def quad(n):
        func_val = (n**2) + n + 41
        return func_val

    def main():
        endProgram = False
        while (endProgram == False):
            total_primes = 0
            num_terms = int(input("Enter a number (-1 to exit)\n --> "))

            if num_terms == -1:
                endProgram = True
            else:
                for n in range(1, num_terms + 1):

                    isprime = True
                    y = quad(n)

                    for i in range (2, y//2):
                        if (y % i == 0):
                            isprime = False

                    if (isprime == True):
                        #print(n , ": ", y , "\n",sep='')
                        total_primes += 1

                print("Total primes in ", n, " terms: " ,total_primes,sep='')
                print("Total composites in ", n, " terms: "\
                      , num_terms - total_primes,"\n",sep='')



    main()

2 个答案:

答案 0 :(得分:0)

您需要更改

for (int i = 2; i <= y; i++) {
            if (y % i == 0)
                isPrime = false;
        }

for (int i = 2; i < y; i++) {
            if (y % i == 0)
                isPrime = false;
        }

不幸的是,您迭代到y,并且y总是可以被y整除。

答案 1 :(得分:0)

Python:

                for i in range (2, y//2):
                    if (y % i == 0):
                        isprime = False

C ++:

    for (int i = 2; i <= y; i++) {
        if (y % i == 0)
            isPrime = false;
    }

后者迭代iy,并且y%y为0。