如何确定 c 中总 sweat/respiration 损失的范围

How to fix the scope for gross sweat/respiration loss in c

该程序应该将液体摄入量添加到总呼吸损失中,但它并没有这样做。问题就在第二个 switch 语句之前。我必须将 F1 初始化为 0.0,否则程序无法编译。

#include <stdio.h>
#include <ctype.h>
#include <unistd.h>

int main(void)
{
float W1;
printf("Prerun Weight (lbs): ");
scanf("%f", &W1);

float W2;
printf("Postrun Weight (lbs): ");
scanf("%f", &W2);

float NL = W1 - W2;
printf("Net Loss: %.2f lbs\n", NL);

char pitStop;
float P;
float S;
pitStop:
printf("Pit stops? (Y/N): ");
scanf(" %c", &pitStop);
switch (toupper(pitStop))
{
    case 'Y':
    printf("Ounces lost: ");
    scanf("%f", &P);
    S = NL - (P / 16);
    printf("Sweat/Respiration loss: %.2f lbs\n", S);
    break;
    case 'N':
    S = NL - 0;
    printf("Sweat/Respiration loss: %.2f lbs\n", S);
    break;
    default:
    printf("Invalid input\n");
    goto pitStop;
    break;
}
// problem is here
char fluidIntake;
float F1 = 0.0;
float G1 = (S * 16) + F1;
float G2 = ((S * 16) + F1) / 16;
fluidIntake:
printf("Fluid Intake? (Y/N): ");
scanf(" %c", &fluidIntake);
switch (toupper(fluidIntake))
{
    case 'Y':
    float F1 = 0.0;
    printf("Ounces drank: ");
    scanf("%f", &F1);
    G1 = (S * 16) + F1;
    float G2 = ((S * 16) + F1) / 16;
    printf("Gross sweat/respiration loss: %.2f oz\n", G1);
    sleep(1);
    printf("Gross sweat/respiration loss: %.2f lbs\n", G2);
    sleep(1);
    break;
    case 'N':
    float G1 = S * 16;
    float G2 = ((S * 16) + 0) / 16;
    printf("Gross sweat/respiration loss: %.2f oz\n", G1);
    sleep(1);
    printf("Gross sweat/respiration loss: %.2f lbs\n", G2);
    sleep(1);
    break;
    default:
    printf("Invalid input\n");
    goto fluidIntake;
    break;
}

float M;
printf("Minutes run: ");
scanf("%f", &M);
float H = M / 60;
sleep(1);
printf("Hours run: %.2f\n", H);

float DM;
sleep(1);
printf("Distance run (mi): ");
scanf("%f", &DM);
float DK = DM * 1.60934;
sleep(1);
printf("Distance run (km): %.2f\n", DK);

float SR1 = G1 / M;
sleep(1);
printf("Sweat rate 1: %.2f oz per min\n", SR1);
sleep(1);
float SR2 = G2 / H;
printf("Sweat rate 2: %.2f lb per hour\n", SR2);
sleep(1);
float SR3 = G1 / DK;
printf("Sweat rate 3: %.2f oz per km\n", SR3);
sleep(1);
float SR4 = G1 / DM;
printf("Sweat rate 4: %.2f oz per mi\n", SR4);
}

问题的根源是在定义G1和G2时,你已经计算了它们

float F1 = 0.0;
float G1 = (S * 16) + F1;
float G2 = ((S * 16) + F1) / 16;

这是无用且错误的。只需定义变量,等到您阅读 F1 并执行计算。我最近不止一次看到这种奇怪的模式(在声明变量时定义公式,但在已知项的值之前),想知道为什么会这样。

你程序的一个令人担忧的方面不仅是你使用了 goto(在我看来,只有当你没有其他合理的选择时才应该使用它),而且你的 goto 跳转 在 switch 语句 之外。你真的应该重写那个逻辑,这是自找麻烦。