哨兵控制循环中变量的正确初始化和函数的后续顺序是什么?
What is the correct initialization of a variable and subsequent order of a function in a sentinel-controlled loop?
我是 C++ 的新手,我写这段代码是为了练习,似乎无法理解为什么我的代码在输入标记值后仍然循环。
示例输出:请输入您的销售额或-1 以退出:25100 您当月的薪水是:$31110.00 请输入您的销售额或-1 以退出:-1 您当月的薪水是:$3499.00 –
这是我的代码:
#include <stdio.h>
#include <math.h>
#define MIN 25000
#define COMP .10
#define BASPAY 3500
//Function Prototypes
double MonthSales(void);
double CalcPay(double sales);
//Begin Main
int main(void)
{
//declare variables
double sales = 0;
// Begin Program with sentinel value for exit
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
//The line above still runs after I input -1 :S.
}
}
//Function for sales
double MonthSales(void)
{
double sales;
printf("Please enter your sales amount or -1 to exit:\n");
scanf("%lf", &sales);
return sales;
}
//Function for total Pay
double CalcPay(double sales)
{
double pay;
double commission;
if (sales > MIN)
{
commission = sales * COMP;
pay = commission + sales + BASPAY;
}
else
{
pay = sales + BASPAY;
}
return pay;
}
在此循环中:
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}
控制表达式 sales != -1
在循环的每次迭代之前计算。它不是连续评估的,也不是在迭代内的点评估的。 sales != -1
变为假时,循环不会自动停止。
相反,您必须在希望控制流更改的位置测试 sales
的值。例如,您可以这样做:
while (1)
{
sales = MonthSales();
if (sales == -1)
break;
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}
我是 C++ 的新手,我写这段代码是为了练习,似乎无法理解为什么我的代码在输入标记值后仍然循环。
示例输出:请输入您的销售额或-1 以退出:25100 您当月的薪水是:$31110.00 请输入您的销售额或-1 以退出:-1 您当月的薪水是:$3499.00 –
这是我的代码:
#include <stdio.h>
#include <math.h>
#define MIN 25000
#define COMP .10
#define BASPAY 3500
//Function Prototypes
double MonthSales(void);
double CalcPay(double sales);
//Begin Main
int main(void)
{
//declare variables
double sales = 0;
// Begin Program with sentinel value for exit
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
//The line above still runs after I input -1 :S.
}
}
//Function for sales
double MonthSales(void)
{
double sales;
printf("Please enter your sales amount or -1 to exit:\n");
scanf("%lf", &sales);
return sales;
}
//Function for total Pay
double CalcPay(double sales)
{
double pay;
double commission;
if (sales > MIN)
{
commission = sales * COMP;
pay = commission + sales + BASPAY;
}
else
{
pay = sales + BASPAY;
}
return pay;
}
在此循环中:
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}
控制表达式 sales != -1
在循环的每次迭代之前计算。它不是连续评估的,也不是在迭代内的点评估的。 sales != -1
变为假时,循环不会自动停止。
相反,您必须在希望控制流更改的位置测试 sales
的值。例如,您可以这样做:
while (1)
{
sales = MonthSales();
if (sales == -1)
break;
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}