# 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;
}
我想运行此代码,但它在定义函数时显示错误。它显示总数未定义。
您应该将“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 代替。