函数返回不返回值给main [英] Function return not returning a value to main

查看:24
本文介绍了函数返回不返回值给main的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我在 C++ 中摆弄函数的第一个任务——我认为我理解这是因为它们与 C# 中的方法非常相似.但是,尽管我的 main 调用我的函数很好,并且函数运行并返回到 main - 它不会发回它在返回时调用的变量信息.我不确定我做错了什么 - 它似乎设置得当(IE - 就像我书中的示例代码一样)这是主要代码...

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.
";
    cin>>division;

    getSales(division);
    retrieveSales=sales1;

    cout<<"Enter second division.
";
    cin>>division2;

    getSales(division2);
    retrieveSales=sales2;
    cout<<"Print Sales"<<sales2;

    cout<<"Enter third division.
";
    cin>>division3;

    getSales(division3);
    retrieveSales=sales3;
    cout<<"Print Sales"<<sales3;

    cout<<"Enter fourth division.
";
    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.
";
        cin>>retrieveSales;
    }
    system("pause");
    return retrieveSales;
}

如何让我的函数将retrieveSales 的值返回到main 中的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆