【问题标题】:Retrieving A Value From A Void Function从无效函数中检索值
【发布时间】:2021-12-28 02:40:42
【问题描述】:

我的一位教授最近给我一个任务,我必须编写一段代码,在其中提示薪水、服务年限,然后根据这两条信息计算奖金。我使用过声明为双精度的函数,但这是我第一次使用 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;
}

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

【问题讨论】:

  • 将指针传递给第一个函数 (GetInput())。将值传递给第二个函数 (CalcRaise())。
  • 我使用 & 来尝试引用变量,但我对如何将它们传递给函数感到有些困惑,比如将语法放在哪里
  • 奇怪的奖金方案:服务0年或1年的人获得2%;服务6-9年的获得5%,服务2-5年的和服务10年或以上的获得10%。幸运的是,这只是课堂练习。

标签: c linux unix


【解决方案1】:

将所有变量设为全局变量,并在初始阶段初始化这些变量。

#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;
}

【讨论】:

  • 我似乎总是忽略最简单的解决方案。谢谢
  • 全局变量通常不是一个好主意。它们在这里很容易避免,也应该在这里避免。
  • 初级水平就够了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 2020-09-03
  • 2020-02-18
  • 1970-01-01
相关资源
最近更新 更多