0
int smallest(int x, int y, int z)
{
    int smallest = x;
    if (y < smallest)
        smallest = y;
    if (z < smallest)
        smallest = z;
    return smallest;
}

void printmessage(int smallest)
{
    int w = 0;
    if(smallest < 0 || smallest >= 10)
        cout << "it is not possible to print the message in this case" << endl;
    else
    {
        for(w < 0 ||w > 10; w < smallest; w++)
            cout << "No" << endl;
        cout << endl << endl;
    }
}

这基本上只是读取 3 个值并找到最小的值。根据最小值打印“否”消息。如果是 5,“否”将被打印 5 次。不知道如何修复我声明最小的部分printmessage。有人可以帮我解决吗?

4

2 回答 2

0

根据您的评论,您只需要修复for循环的第一部分:

void printmessage(int smallnum) {
    if(smallnum < 0 || smallnum >= 10) {
        cout << "it is not possible to print the message in this case" << endl;
    } else {
        for(int w = 0; w < smallnum; w++) {
            cout << "No" << endl;
        }
    }
}

注意参数名称的变化——现在,你已经有了一个名为 的函数smallest(),所以你也不应该用这个名字创建一个变量,否则你会发生奇怪的事情。您的smallest()函数本身也是如此 - 将第一行更改int smallest = x;int smallnum = x或类似,并在函数的其余部分更改对它的引用。

而且,正如 namfuak 在评论中指出的那样,更改printmessage(smallest);printmessage(smallest(x, y, z));,否则您将尝试传递函数的地址,而不是其结果。

在一个完整的工作示例中:

#include <iostream>

void printmessage(int smallnum) {
    if(smallnum < 0 || smallnum >= 10) {
        std::cout << "it is not possible to print the message in this case"
                  << std::endl;
    } else {
        for(int w = 0; w < smallnum; ++w) {
            std::cout << "No" << std::endl;
        }
    }
}

int main(void) {
    printmessage(5);
    return 0;
}

输出:

paul@local:~/src/cpp/scratch$ ./smallest
No
No
No
No
No
paul@local:~/src/cpp/scratch$
于 2013-10-21T04:09:21.590 回答
0
for(w < 0 ||w > 10; w < smallest; w++)

第一部分实际上毫无意义,而从技术上讲,执行该语句时 for 循环中的第一条语句通俗地用于初始化和/或分配循环控制变量。在你的情况下,你可能想使用这个:

for(int w = 0; w < smallest; w++)

这将在循环范围内初始化变量“w”,而不是在函数范围内(因此在循环退出后,“w”将被丢弃)。由于您只需要在循环中使用它,因此这应该是您正在寻找的。

如果要检查 w 是否也不小于 0 或大于 10,可以使用以下循环:

for(int w = 0; w < 0 || w > 10, w < smallest; w++)

如果您以后需要它(或在其他不需要循环控制变量的情况下),您也可以将初始 w 保留在函数范围中,并在循环声明中的该空间中使用空白语句:

for(; w < smallest; w++)
于 2013-10-21T04:12:27.007 回答