c - 从无效函数中检索值
问题描述
最近,我的一位教授给了我一个任务,我必须编写一段代码,在其中提示薪水、服务年限,然后根据这两条信息计算奖金。我使用过声明为双精度的函数,但这是我第一次使用 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;
}
正如我所提到的,我只是在弄清楚如何保存我的第一个函数中的值并使用它们来计算奖金时遇到了麻烦。任何帮助表示赞赏。-谢谢
解决方案
使所有变量成为全局变量,并在起始阶段本身初始化这些变量。
#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;
}
推荐阅读
- anaconda - Conda virtual environment keeps using wrong version of Python
- java - How do I initialize an array of type String within a constructor in Java?
- docker - rename .docker_temp_134954455 seal:3.4.0.tar: protocol error when using Docker to save image
- snowflake-cloud-data-platform - 雪花随用随付
- javascript - 如果条件满足,如何仅将数组元素复制到电子表格
- spring-webflux - 如果单声道为空,怎么会有异常?
- docker - Docker没有在Linux上同步文件
- ffmpeg - ffmpeg mkv to mp4转换器会丢失部分音频,如何在python中配置?
- file-type - Geany 在打开时不会自动检测自定义文件类型
- r - 为什么将 emmeans 与 data.frame 对比而不报告正确的 p 值?