【问题标题】:Using functions in C++ (void, double, int)在 C++ 中使用函数(void、double、int)
【发布时间】:2013-06-08 13:03:09
【问题描述】:

我正在慢慢尝试自己学习 C++,但在使用函数时遇到了困难。我确实找到了解决最初问题的方法,但我不知道为什么我不能按照我最初打算的方式去做。这是工作程序。

// ex 6, ch 2
#include <iostream> 
using namespace std; 

void time(int, int);
int main() 
{
int h, m; 
cout << "Enter the number of hours: "; 
cin >> h; 
cout << endl; 
cout << "Enter the number of minutes: "; 
cin >> m; 
cout << endl; 
time(h, m); 

cin.get();
cin.get();
return 0; 
} 

void time(int hr, int mn)
{
 cout << "The time is " << hr << ":" << mn;  
}

这就是我想要的方式。

// ex 6, ch 2
#include <iostream> 
using namespace std; 

void time(int, int);
int main() 
{
int h, m; 
cout << "Enter the number of hours: "; 
cin >> h; 
cout << endl; 
cout << "Enter the number of minutes: "; 
cin >> m; 
cout << endl; 
cout << "The time is " << time(h, m); 

cin.get();
cin.get();
return 0; 
} 

void time(int hr, int mn)
{
 cout << hr << ":" << mn;  
}

在我的脑海中,它们都会返回相同的东西,但我的编译器却不这么认为(我想知道为什么)。

编辑:出于某种奇怪的原因,它似乎像这样工作。

cout << "The time is "; 
time(h, m); 

如果仅此而已,那只会让我更加困惑。

【问题讨论】:

    标签: c++ function void


    【解决方案1】:
    cout << "The time is " << time(h, m); 
    

    time 不返回任何内容,但是在这种情况下向cout 发送一些内容需要它返回一个值(在这种情况下可能是一个字符串),而不是让time 函数直接调用cout

    【讨论】:

      【解决方案2】:

      您需要编辑您的time-函数以返回string。我正在使用stringstream 将 int 转换为字符串。

      #include <sstream>
      ...
      string time(int, int);
      
      ...
      
      string time(int hr, int mn)
      {
          stringstream sstm;
          sstm << hr << ":" << mn;
          string result = sstm.str();
          return result;
      }
      

      现在可以直接使用了,比如:

      cout << "The time is " << time(h, m); 
      

      【讨论】:

      • 尝试将其更改为字符串。由于某种原因,它没有返回任何东西。 (不过没有编译错误)。另外,练习的描述说我应该使用 void 函数来调用函数。
      • 你记得编辑标题中的声明吗?查看我的编辑
      • 是的。做过某事。没有结果。该程序运行完美,但是当它应该打印出 cout
      • 对不起,我太傻了。您不能像那样将 int 转换为stirng,例如可以使用stringstream。我给你看
      • 这实际上是我第一次使用字符串流,但我会记住它作为一个选项。是否也有任何方法可以使用 void 函数?这是我开始的练习“编写一个要求用户输入小时值和分钟值的程序。然后 main() 函数应该将这两个值传递给一个类型 void 函数,该函数以所示格式显示这两个值在以下示例运行中"
      猜你喜欢
      • 2011-05-28
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 2011-12-04
      • 1970-01-01
      • 1970-01-01
      • 2014-03-20
      相关资源
      最近更新 更多