【问题标题】:Calling a Void funtion inside a for-loop C++在 for 循环 C++ 中调用 Void 函数
【发布时间】:2021-02-21 14:35:06
【问题描述】:

这是我在 StackOverflow 上的第一篇文章!我的 Intro C++ 课程的项目有问题。我在 for 循环中调用时收到 E0349 错误,“没有运算符与这些操作数匹配”。我在这里查看了类似的问题,但没有找到解决方案。如果我的格式有任何错误或不太了解,我深表歉意。这是我的第一堂编程课。

我的代码:

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

void disp2xInt(int num);

int main() {
    // Do "Press any key to continue..." on exit
    atexit([] {system("pause"); });

    // Print out your name and course
    cout << "Jacob" << endl;
    cout << "ELET115N" << endl << endl;

    for (int i = 0; i < 5; i++) { 
        cout << disp2xInt(i) << "\n";
        cout << "Hello world!!!\n"; 
    }
    disp2xInt(9);

    return 0;
}

void disp2xInt(int n) {
    cout << "2 x " << n;
    cout << " = " << n * 2; 
    cout << endl;
}

【问题讨论】:

  • disp2xInt 返回void 时,您希望coutcout &lt;&lt; disp2xInt(i) &lt;&lt; "\n"; 中打印什么?只需调用它disp2xInt(i)。注意:我有信心,肯定有重复的,因为我每周都会看到这样的问题,但我懒得去找它:/

标签: c++ function loops error-handling


【解决方案1】:

您不能cout 方法返回 void。此外,在这种情况下它是不必要的,因为方法本身已经调用了cout。做吧:

int main() {
    // Do "Press any key to continue..." on exit
    atexit([] {system("pause"); });

    // Print out your name and course
    cout << "Jacob" << endl;
    cout << "ELET115N" << endl << endl;

    for (int i = 0; i < 5; i++) { 
        disp2xInt(i);
        cout << "Hello world!!!\n"; 
    }
    disp2xInt(9);

    return 0;
}

【讨论】:

  • 完全有道理,甚至没有意识到这一点。谢谢!
【解决方案2】:
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int disp2xInt(int num);

int main() {

int x;
// Print out your name and course
cout << "Jacob" << endl;
cout << "ELET115N" << endl << endl;

for (int i = 0; i < 5; i++) {
    x=disp2xInt(i) ;
    cout << x<<endl;;
    cout << "Hello world!!!"<<endl<<endl;
}
disp2xInt(9);

return 0;
}

int disp2xInt(int n) {
cout << "2 x " << n;
cout << " = " << n * 2;
cout << endl;
return n;
}

【讨论】:

  • 我也喜欢这个主意。他们都应该工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
  • 2014-11-26
相关资源
最近更新 更多