Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ UVA 3n+;1(prob 100)回答错误,但所有测试用例均通过_C++ - Fatal编程技术网

C++ UVA 3n+;1(prob 100)回答错误,但所有测试用例均通过

C++ UVA 3n+;1(prob 100)回答错误,但所有测试用例均通过,c++,C++,我已经看到了一些关于stackoverflow等的问题,并尝试修复上面提到的提示以获得正确的代码。例如,现在我检查a>b。或者我使用long-long而不是简单的int。但还是得到了错误的答案。我的答案怎么了 我的代码: #include <iostream> using namespace std; int count_steps(long long int num) { int counter = 1; while(num != 1) {

我已经看到了一些关于stackoverflow等的问题,并尝试修复上面提到的提示以获得正确的代码。例如,现在我检查
a>b
。或者我使用
long-long
而不是简单的
int
。但还是得到了错误的答案。我的答案怎么了

我的代码:

#include <iostream>
using namespace std;

int count_steps(long long int num)
{
    int counter = 1;
    while(num != 1)
    {
        if (num % 2 == 1)
            num = 3*num + 1;
        else
            num /= 2;

        counter++;
    }

    return counter;
}

int max_between(long long int a , long long int b)
{
    int max=0,step;
    for(long long int i = a; i <= b; i++)
    {
        if ((step = count_steps(i)) > max)
            max = step;
    }
    return max;
}

int main()
{
    int max=0,a,b,step;
    cin >> a;
    cin >> b;
    if (a >= b)
        cout << a << ' ' << b << ' ' << max_between(b,a) << endl;
    else
        cout << a << ' ' << b << ' ' << max_between(a,b) << endl;
    return 0;   
}

对代码的一些注释:

您将
a
b
读作
int
,尽管在方法中将它们用作
long-long-int
。那是胡说八道,把它们当作要使用的类型来读

虽然不太可能,但您可能会遇到溢出。为了避免这种情况,您可以使用
无符号long-long
将整数的范围扩大一倍

从数学上讲,你做得太多了

对于奇数整数
n=2k+1
,结果
3n+1
将始终为偶数:
3n+1=3(2k+1)+1=6k+4
。因此,您可以将奇数
n
的情况与以下除以2的情况结合起来。其结果是
3k+2
,即
k+1
大于
n
。在C++中使用整数运算,这可以用<代码> n+=(n/2)+1 < /> >作为<代码> n/2 < /代码>将评估为<代码> k< /代码> .< 代码不被接受的另一个可能原因是输入/输出。您必须遵循平台的确切要求


代码将忽略问题描述的以下部分:

输入将由一系列成对的整数组成

这个问题很容易解决

int main()
{
    int max=0,a,b,step;
    while ( cin >> a >> b )
    {
       std::cout << a << ' ' << b << ' ';
       if (a >= b)
       {
           std::cout << max_between(b,a);
       }
       else
       {
           std::cout << max_between(a,b);
       }
       std::cout << std::endl;
    }
    return 0;   
}
intmain()
{
int max=0,a,b,步长;
而(cin>>a>>b)
{

std::cout输入可能由多对组成。您只是在读取一对。问题是“一系列对”的整数应该给您,但它没有从一开始就指定对的数量。@Pooya Abhishek是对的:“输入将由一系列对的整数组成”.这是你唯一的问题。如果使用32位整数类型,网站还保证不会溢出,所以你甚至不需要长整型。是的,你是对的。tnx@AbhishekBansal和stefan!
int main()
{
    int max=0,a,b,step;
    while ( cin >> a >> b )
    {
       std::cout << a << ' ' << b << ' ';
       if (a >= b)
       {
           std::cout << max_between(b,a);
       }
       else
       {
           std::cout << max_between(a,b);
       }
       std::cout << std::endl;
    }
    return 0;   
}