将伪代码翻译成c++

Translate pseudo code into C++

本文关键字:c++ 翻译 伪代码      更新时间:2023-10-16

我得到了一个伪代码来翻译成c++:

    Set a Boolean variable “first” to true.
    While another value has been read successfully
          If first is true
          Set the minimum to the value.
          Set first to false.
          Else if the value is less than the minimum
          Set the minimum to the value.
    Print the minimum

下面是我的代码:

bool first = true;
bool read_value = true;
int value = 0;
int minimum = 0;
cout << "Enter an integer : " ;
cin >> value;
while(cin.hasNextInt())   // error here
{
    cout << "Enter another integer : " ;
    cin >> minimum;
    if( first == true){
        minimum = value;
        first = false;
    }else if ( value < minimum){
        minimum = value;
    }
}
cout << minimum;
system("PAUSE");
return 0;

在hasNextInt那里有错误。我真的不知道伪代码想要什么。有人能给我解释一下吗?

在标准c++库中没有hasNextInt()函数(这就是为什么你不能编译)。但是在Java中有一个!

这更接近你想要的代码:

cout << "Enter an integer : " ;
while( cin >> value )
{
    if( first == true){
        minimum = value;
     first = false;
    }else if ( value < minimum){
        minimum = value;
    }
    cout << "Enter another integer : " ;
}

这是愚蠢的伪代码。我们可以做得更好没有这些无用的bool…

int min = std::numeric_limits<int>::max();
for(int val; cin >> val)
{
    if(val < min)
        min = val;
}
cout << "Minimum: " << min << 'n';