我已经用C ++开始了一个项目来练习参数的使用,我在代码中遇到了一个问题,我不太清楚为什么我会得到我的价值观。我得到了。
这是我的代码:
当我运行它时,我从displayFinalData
输出的值为0而不是我期望的值(这应该是转换的等等)。
#include <iostream>
using namespace std;
int main()
{
int numInEuros = 0;
char answer = 'Y';
double sumEuro = 0;
double priceEuro = 0;
int number = 0;
while ((answer == 'Y') || (answer == 'y'))
{
void processAPrice();
processAPrice();
void calculateSum(double priceInEuros, double& sumInEuros);
calculateSum(priceEuro, sumEuro);
cout << "\nDo you wish to continue? (Y/N): ";
cin >> answer;
number += 1;
}
void displayFinalData(double sumInEuros, int number);
displayFinalData(sumEuro, number);
system("pause");
return 0;
}
void processAPrice()
{
double pricePounds;
double priceEuro;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceEuro);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceEuro);
}
void getPriceInPounds(double& priceInPounds)
{
cout << ("\nEnter price in pounds: \x9C");
cin >> priceInPounds;
}
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros)
{
double conversionRate = 0.82;
priceInEuros = (priceInPounds / conversionRate);
}
void showPriceInEuros(double priceInPounds, double priceInEuros)
{
cout << ("\nThe Euro value of \x9C") << priceInPounds << " is EUR " << priceInEuros << "\n";
}
void calculateSum(double priceInEuros, double& sumInEuros)
{
sumInEuros += priceInEuros;
}
void displayFinalData(double sumInEuro, int number)
{
cout << "\nThe total sum is: EUR " << sumInEuro << "\n";
cout << "\nThe average is: EUR " << (sumInEuro / number) << "\n\n";
}
答案 0 :(得分:1)
您在processAPrice()函数中单独声明priceEuros变量,并在用户输入以磅为单位的价格后更新,但main()中的priceEuro变量未受影响,并且将sumEuro递增0。
如果将main中的priceEuros变量传递给processAPrice()函数,它将起作用
void processAPrice(double& priceInEuros)
{
double pricePounds;
void getPriceInPounds(double& priceInPounds);
getPriceInPounds(pricePounds);
void convertPriceIntoEuros(double priceInPounds, double& priceInEuros);
convertPriceIntoEuros(pricePounds, priceInEuros);
void showPriceInEuros(double priceInPounds, double priceInEuros);
showPriceInEuros(pricePounds, priceInEuros);
}
答案 1 :(得分:0)
我猜测您要更新priceEuros
变量吗?问题是它是本地变量。不同函数中的局部变量没有关系,即使它们具有相同的符号名称。
对于要在函数之间共享的变量,您需要将它们设置为全局,即将它们声明为超出任何函数的范围。