首页 > 解决方案 > 在 C++ 的 void 函数中可以有很多参数吗?

问题描述

我是初学者,所以请善待:)

我已经使用全局变量使程序正常工作。但是我想尝试使用局部变量,因为全局变量看起来很乱,而且我还发现总是使用它是一种不好的做法。该程序使用局部变量运行,但不能正常工作。我在显示 void 函数 funcDataSummary 下的结果时遇到问题。void funcDataSummary 有效,用户输入的 (float numberOfRooms, float wallSpace, float costOfPaint,...) 的值是正确的,但 (..., float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost) 的值, float totalCost) 当它们应该有值时为 0。

使用全局变量输出: 使用全局变量输出

使用局部变量输出: 使用局部变量输出

#include <iostream>
#include <iomanip>
#include <windows.h>

using namespace std;

// function prototype
void funcDataSummary(float, float, float, float, float, float, float, float);

// void function called in int main()
funcDataSummary(numberOfRooms, wallSpace, costOfPaint, gallonsOfPaint, totalCostOfPaint, hoursOfLabor, laborCost, totalCost);

// void function
void funcDataSummary(float numberOfRooms, float wallSpace, float costOfPaint, float gallonsOfPaint, float totalCostOfPaint, float hoursOfLabor, float laborCost, float totalCost)
{
    cout << "DETAILS" << endl;
    cout << "Number of Rooms = " << funcNumberOfRooms(numberOfRooms) << endl;
    cout << "Wall Dimension = " << funcWallSpace(wallSpace) << " square feet" << endl;
    cout << "Paint Cost = Php " << funcCostOfPaint(costOfPaint) << endl;
    cout << "Gallons of Paint = " << funcGallonsOfPaint(gallonsOfPaint);
    // singular and plural forms of units
    if(funcGallonsOfPaint(gallonsOfPaint) > 1)
    {
        cout << " Gallons" << endl;
    }
    else 
    {
        cout << " Gallon" << endl;
    }    
    cout << "Total Paint Cost = Php " << << funcTotalCostOfPaint(totalCostOfPaint) << endl;
    cout << "Labor hours = " << funcHoursOfLabor(hoursOfLabor);
    // singular and plural forms of units
    if(funcHoursOfLabor(hoursOfLabor) > 1)
    {
    cout << " hours" << endl;
    }
    else 
    {
        cout << " hour" << endl;
    }
    cout << "Labor Cost = Php " << funcLaborCost(laborCost) << endl; 
    cout << "TOTAL COST = Php " << funcTotalCost(totalCost) << endl;
}

标签: c++functionglobal-variablesvoidlocal-variables

解决方案


虽然没关系,但它使您的代码有点复杂。如果可能的话,最好将一个或多个相互关联的变量分组,struct或者class将这些对象(或指针/引用/常量引用,如果需要)作为参数传递。


推荐阅读