什么是 void 函数,如何在我的代码中使用它们? [已关闭]

问题描述 投票:0回答:1

这段代码既可以用于倒计时,也可以用于以一定间隔进行递增计数,但我应该在其中包含 2 个 void 函数,我该怎么办?他们已经在那里了吗?


#include <iostream>

using namespace std;

int main()
{
   float strpt;
   float stppt;
   float intrvl;


   cout << "please enter a start point: ";
   cin >> strpt;
   cout << "please enter a stop point: ";
   cin >> stppt;
   cout << "please anter an interval: ";
   cin >> intrvl;
   if (intrvl <= 0)
      cout << "Sorry, that interval is invalid";

   else for (int i = strpt; i <= stppt; i = i + intrvl) {
      cout << i << "\n";
   }

   for (int i = strpt; i >= stppt; i = i - intrvl) {
      cout << i << "\n";
   }

   return 0;
}

这是用C++编写的 我不知道如何使用 void 函数,这段代码可以工作,但它没有像我也需要的 void 函数。

c++ void
1个回答
1
投票

函数有一个返回类型,从该函数返回时必须填写该返回类型。这是通过

return
语句后跟返回值来完成的。对于 void 函数,返回类型为 void,这意味着函数不返回任何值,因此从此类函数返回是通过不带值的
return
语句或到达函数作用域末尾来完成的。

在练习中,您可以添加 2 个 void 函数:

void get_input(float& startpoint, float& stoppoint, float& interval);
void print_output(float startpoint, float stoppoint, float interval);
,它们从主函数调用,并且包含现在在主函数中找到的代码。

请注意,引用传递给第一个函数,因此可以更改变量,但不会传递给第二个函数,因为变量不会更改。

© www.soinside.com 2019 - 2024. All rights reserved.