这段代码有什么问题,它显示总计未定义

问题描述 投票:0回答:1
# include <iostream>

using namespace std;

double getTotal(double prices[], int size); //Declaration of a function.


int main(){

    double prices[] = {5.63, 4.21, 75, 6.14, 2.4};
    int size = sizeof(prices) / sizeof(prices[0]);

    double total = getTotal(prices, size); // Call a function

    cout << "$ " << total << '\n';

    return 0;
}

double getTotal(double prices[], int size) //Define a function.
{
    for (int i = 0; i < size; i++)
    {
        total += prices[i];
    }

    return total;
}

我想运行此代码,但它在定义函数时显示错误。它显示总数未定义。

c++ c++11 visual-c++ c++17 c++14
1个回答
0
投票

您应该将“total”变量从主函数作用域提取到全局作用域。

using namespace std;

double total = 0;
double getTotal(double prices[], int size); //Declaration of a function.

int main(){

    double prices[] = {5.63, 4.21, 75, 6.14, 2.4};
    int size = sizeof(prices) / sizeof(prices[0]);

    total = getTotal(prices, size); // Call a function

    cout << "$ " << total << '\n';    

    return 0;
}

double getTotal(double prices[], int size) //Define a function. {

    for (int i = 0; i < size; i++)
    {
        total += prices[i];
    }

    return total;
}

使用 namespace::std 是不好的做法。 使用 std::cout 代替。

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