首页 > 解决方案 > 从无效函数中检索值

问题描述

最近,我的一位教授给了我一个任务,我必须编写一段代码,在其中提示薪水、服务年限,然后根据这两条信息计算奖金。我使用过声明为双精度的函数,但这是我第一次使用 void 函数。我无法理解如何获得第一个函数来保存提示的服务年限和薪水值,然后在下一个函数中使用这些值来计算奖金。这是我目前拥有的:

#include <cstdio>

void GetInput()
{
double salary;
int years_service;

printf("Enter your salary: ");
scanf("%lf", &salary);

printf("How many years have your served for us? ");
scanf("%d", &years_service);
}

void CalcRaise()
{
//I initialized salary and years_service because they would not compile 
//otherwise. As expected, it does run but since they are set to 0, the 
//bonus will be zero.

double salary = 0;
int years_service = 0;

double bonusA;
double bonusB;
double bonusC;

bonusA = salary * .02;
bonusB = salary * .05;
bonusC = salary * .10;

if ( years_service < 2)
{
    printf("Here is your bonus: %lf", bonusA);
}

else if ( years_service > 5 && years_service < 10)
{
    printf("Here is your bonus: %lf", bonusB);
}

else
{
    printf("Here is your bonus: %lf", bonusC);
}
return;
}


int main()
{

GetInput();
CalcRaise();

 return 0;
}

正如我所提到的,我只是在弄清楚如何保存我的第一个函数中的值并使用它们来计算奖金时遇到了麻烦。任何帮助表示赞赏。-谢谢

标签: clinuxunix

解决方案


使所有变量成为全局变量,并在起始阶段本身初始化这些变量。

#include <stdio.h>
#include <stdlib.h>

double salary = 0;
int years_service = 0;
double bonusA;
double bonusB;
double bonusC;

void GetInput()
{
    printf("Enter your salary: ");
    scanf("%lf", &salary);
    printf("How many years have your served for us? ");
    scanf("%d", &years_service);
}

void CalcRaise()
{
    bonusA = salary * .02;
    bonusB = salary * .05;
    bonusC = salary * .10;
    if (years_service < 2)
    {
        printf("Here is your bonus: %lf", bonusA);
    }
    else if (years_service > 5 && years_service < 10)
    {
        printf("Here is your bonus: %lf", bonusB);
    }
    else
    {
        printf("Here is your bonus: %lf", bonusC);
    }
}

int main()
{  
    GetInput();
    CalcRaise();
    return 0;
}

推荐阅读