函数返回未将值返回给main [英] Function return not returning a value to main
问题描述
所以,这是我对C ++中的函数的第一次赋值-我认为我理解它们是因为它们与C#中的方法非常相似.但是,尽管我的main很好地调用了我的函数,并且该函数运行并返回到main-它不会在返回时将其调用的变量信息发送回去.我不确定自己做错了什么-似乎已正确设置(即-像我书中的示例代码一样可以退货)这是主要代码...
So, this is my first assignment fiddling with functions in C++ - which I thought I understood being as they're rather similar to methods with C#. But, although my main calls my function fine, and the function runs and returns to the main - It doesn't send back the variable information that it called when it returns. I'm not exactly sure what I've done wrong - it appears to be set up appropriately (IE - Like the sample code in my book for a return) Here's the main code...
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
double retrieveSales=0, sales1=0, sales2=0, sales3=0, sales4=0;
string division, division2, division3, division4;
double getSales(string);
cout<<"Enter division.\n";
cin>>division;
getSales(division);
retrieveSales=sales1;
cout<<"Enter second division.\n";
cin>>division2;
getSales(division2);
retrieveSales=sales2;
cout<<"Print Sales"<<sales2;
cout<<"Enter third division.\n";
cin>>division3;
getSales(division3);
retrieveSales=sales3;
cout<<"Print Sales"<<sales3;
cout<<"Enter fourth division.\n";
cin>>division4;
getSales(division4);
retrieveSales=sales4;
cout<<"Print Sales"<<sales4;
system("pause");
return 0;
}
这是它调用的函数的代码
And here's the code for the function that it calls
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
double getSales(string division)
{
double retrieveSales;
cout<<"What are the sales for "<<division<<endl;
cin>>retrieveSales;
while(retrieveSales<0.0)
{
cout<<"Please enter a valid sales amount no less than $0.00.\n";
cin>>retrieveSales;
}
system("pause");
return retrieveSales;
}
如何获取函数以将retrieveSales的值返回到主目录中的retrieveSales?
How do I get my function to return the value of retrieveSales to retrieveSales in the main?
推荐答案
在这一行:
getSales(division);
您要放弃返回值,需要将其分配给变量:
You are discarding the return value, you need to assign it to a variable:
sales1 = getSales(division);
这篇关于函数返回未将值返回给main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!