【问题标题】:how could I convert c++ to python [closed]我如何将 c++ 转换为 python [关闭]
【发布时间】:2018-04-30 10:36:01
【问题描述】:
#include <iostream>
using namespace std;

int main() {   
  int n;
  int i;  
  int k; 
  cout << "please insert n";

  cin >> n; k=0 ;

  for (i = n; i > 1; i--) {
    cout << "/n "<< k << "+" << i << "=" << i + k++;
  }

  return 0;     
}  

我正在尝试在 python 中重现上面的代码,但我不确定我做错了什么。我不确定如何从一个数字开始,然后递减直到满足条件。这是我目前所拥有的:

k=0
n=4
for i in range(n)
 if i > 1 :
  i-=1
  k+=1
print(i+k++) 

我做错了什么?

【问题讨论】:

  • 你的 range(n) 应该是 range(n, 1, -1) 并且 Python 中没有这样的运算符 k++ 你需要一个额外的步骤 k += 1
  • 但这并不能修复错误

标签: python c++ algorithm


【解决方案1】:
n = int(input("please insert n : "))
k = 0
for i in range(n,1,-1):
    print('\n',k,'+',i,'=',i+k)
    k=k+1

range 本身解决了一半的问题。剩下的就是格式化和输入数字。

range(n,1,-1) 表示范围从n1 结束,它们之间有一个-1 的步骤。

n, n+(-1), n+(-2),...,1.


您的 C++ 程序生成错误的输出:-

/n 1+4=4/n 2+3=4/n 3+2=4

正确代码:

for(i=n,k=0; i > 1 ; i--,k++){
   cout << "\n "<< k << "+" << i << "=" << i + k;
}

您的意思是C++ 中的\n(换行符)而不是/n

【讨论】:

  • range(n,1,-1) 是什么意思?
  • @moustafasoama 来自the docs: range(start, stop[, step])
  • @coderredoc 非常感谢
【解决方案2】:

你需要一个递减的 for 循环。

# range(4,1,-1) would give a list of [4,3,2]
# for loop iterates through each number.
k = 0
n = 4
# This iterates from n = 4 to 1
# decrementing one step at a time, needn't specifically handle i in your loop body. 
# So i would get values of 4,3,2
for i in range(n,1,-1):
    print(k,i)
    # no ++ operator in python.
    k+=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    相关资源
    最近更新 更多