【问题标题】:No output? C++14没有输出? C++14
【发布时间】:2015-12-22 17:53:45
【问题描述】:

所以我尝试做一个名为 3n+1 的挑战,我必须告诉程序在 n=1 之前必须进行多少次乘法或除法运算,但我没有从程序中得到任何输出。请帮忙? p.s.我正在使用 C++ 14

#include <iostream>
using namespace std;
int n;
int d=0;
int main() {
    cin>> n;
    for(int i=n; i<=1;){
        if(n=1){
            cout<< d;
        }
        else if(n%2==0){
            d++;
            n/2;
        }
        else{
            d++;
            n*3+1;
        }
    }
    return 0;
}

【问题讨论】:

  • 您的代码中甚至没有&lt;&lt; 运算符。
  • cout &lt;&lt; d,而不是cout &gt;&gt; d。投票结束是一个错字。
  • 更改 cout>> 为 cout
  • 你不改变或使用i
  • Get a book and read it。这段代码中有大量可笑的微不足道的错误。

标签: c++ c++14


【解决方案1】:

可能的修复:

#include <iostream>
using namespace std;
int main() {
    int n; // you don't need the values to be global
    int d=0;
    cin>> n;
    for(; ;){ // deleted i because it wasn't used
        if(n<=1){ // compare here, don't assign here
            cout<< d;
            break; // exit the loop
        }
        else if(n%2==0){
            d++;
            n=n/2; // please update n here
        }
        else{
            d++;
            n=n*3+1; // also please update n here
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多