C++中的代码输出出现问题

An issue with an output of a code in C++

本文关键字:问题 输出 代码 C++      更新时间:2023-10-16

我的代码有问题。

我的代码是:

#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int min(int A[], int s)
{
    int x = A[0];
    for (int i = 0; i<s; i++)
        if (A[i]<x)
            x = A[i];
    return x;
}
int max(int A[], int s)
{
    int x = A[0];
    for (int i = 0; i<s; i++)
        if (A[i]>x)
            x = A[i];
    return x;
}

int main()
{
    int Array[10] = { 15,20,8,0,17,14,2,12,10,5 };
    while (1)
    {
        string UserInput;
        cin >> UserInput;
        if (UserInput == "Minimun")
        {
            int Minimum = min(Array, 10);
        }
        if (UserInput == "Maximum")
        {
            int Maximum = max(Array, 10);
        }
        if (UserInput == "Dropped ones")
        {
            int count = min(Array, 10) + 1;
            for (int i = min(Array, 10); i<max(Array, 10) - 1; i++)
                cout << count++ << "n";
        }
    }
    return 0;
}

它没有错误,但它不能像我想要的那样工作。

如果我有一个数组:int array[10]={15,20,8,0,17,14,2,12,10,5};

我在这个数组中找到了最大值和最小值。我想做一个计数器,打印从0到20的值,除了数组中的值。

这意味着输出应该是:

1
3
4
6
7
9
11
13
15
16
18
19

为什么我的代码不打印此输出?

请帮帮我,我不知道这段代码中的错误句子在哪里。提前谢谢。

另一次尝试,但用"cbegin"answers"cend"给出错误:

     #include <iostream>
     #include <vector>
     #include <algorithm>
       using namespace std;
       int main()
         {
         int Array[] = { 15, 20, 8, 0, 17, 14, 2, 12, 10, 5 };
auto Minimum = *min_element( cbegin( Array ), cend( Array ) );
auto Maximum = *max_element( cbegin( Array ), cend( Array ) );
cout << "Min: " << Minimum << 'n';
cout << "Max: " << Maximum << 'n';
for( auto i = 1; i <= 20; ++i ) {
    if( find( cbegin( Array ), cend( Array ), i ) == cend( Array ) ) {
        cout << i << "n";
    }
}
return 0;
 }

如果我正确理解你的帖子。根据您的要求,我将代码从使用向量更改为使用c数组。我拿出了用户输入的东西,给你一个更小的样本来看看。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    int Array[] = { 15, 20, 8, 0, 17, 14, 2, 12, 10, 5 };
    // part of the xutility header
    // better to use cbegin( Array );
    auto begin = &Array[ 0 ];
    // better to use cend( Array );
    auto end = begin + sizeof( Array ) / sizeof( Array[ 0 ] );
    auto Minimum = *min_element( begin, end );
    auto Maximum = *max_element( begin, end );
    cout << "Min: " << Minimum << 'n';
    cout << "Max: " << Maximum << 'n';
    for( auto i = 1; i <= 20; ++i ) {
        if( find( begin, end, i ) == end ) {
            cout << i << "n";
        }
    }
    return 0;
}

它不起作用,因为你的cin只得到第一个单词"Dropped",而不是"Droppedones"。如果你把它变成一个词,似乎效果很好:http://ideone.com/AjtOc7.

如果你想要多个单词,请使用getline

std::string UserInput;
std::getline (std::cin, UserInput);

此外,考虑使用STL库,如答案中提到的库。