c++ - 函数内部cout无法使用
阿神
阿神 2017-04-17 15:33:57
0
1
1300

平台:win10+vs2017
代码1:

#include<iostream>
#include<cstdio>
using namespace std;
int nice(int p, int e, int i, int d) {
    int k = d + 1;
    while ((k % 33) != 0)
    {
        ++k;
    }
    for (; k < 21252; k += 33)
    {
        if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
            return (k - d);
    }
}
int main()
{
    cout << nice(0, 0, 0, 0) << endl;
    system("pause");
    return 0;
}

执行成功。
如果我把nice函数中if语句块的return变成cout,再将函数返回类型变成void。程序不执行该语句。
代码如下:

#include<iostream>
#include<cstdio>
using namespace std;
void nice(int p, int e, int i, int d) {
    int k = d + 1;
    while ((k % 33) != 0)
    {
        ++k;
    }
    for (; k < 21252; k += 33)
    {
        if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
            cout << (k - d) << endl;
    }
}
int main()
{
    nice(0, 0, 0, 0);
    system("pause");
    return 0;
}

请问这是什么原因呢?我第一个代码执行成功不就表示程序逻辑正确并且可以执行到if的语句体吗?为什么把return改成cout语句以后就失败了呢?

阿神
阿神

闭关修行中......

répondre à tous(1)
迷茫

因为没有执行过if分支。

int nice(int p, int e, int i, int d) {
  int k = d + 1;
  while ((k % 33) != 0)
  {
    ++k;
  }
  for (; k < 21252; k += 33)
  {
    if (((k - p) % 23 == 0) && ((k - e) % 28 == 0))
      return (k - d);
  }
  return -1;
}

用我提供的nice代替你样例1中的nice(我只是在最后加上了return -1;没有修改过其他的部分),程序输出将会是-1。这说明if分支没有被执行过,否则函数会提前返回。(33,23和28的最小公倍数是21252,但for将保证每次进入循环体时,k小于21252。)

你样例1中的代码会导致未定义行为。结果一般是返回一个莫名其妙的值。而这个值有可能是你期望的值。

如果你仔细看,vs2017会报一个警告:

Warning C4715 'nice': not all control paths return a value

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!