简体   繁体   English

如何在 C 中退出 Do While 循环后使用在 Do While 循环中输入的值

[英]How to Use A Value Entered in Do While Loop After Exiting the Do While Loop in C

I'm a newbie in C programming.我是 C 编程的新手。 I'm curious to know if it's possible to take a value entered in do while loop and use it outside the loop.我很想知道是否可以在 do while 循环中输入一个值并在循环外使用它。 Tried to code it a few times but it's not working for me.尝试对其进行编码几次,但它对我不起作用。 Appreciate a lot if someone could help me out in this matter.如果有人可以在这件事上帮助我,将不胜感激。

#include <stdio.h>
int main() {
  float salary, hours, bonus;
  float rateperhour = 2.50;
  do {
    printf("Please enter hours worked: ");
    scanf("%f", &hours);
    salary = hours * rateperhour;
    if (salary > 500 && salary < 1000) {
      printf("Range: 5000-10000\n");
    } else {
      hours = 0;
    }
    printf("Salary: %.2f\n", salary);
  } while (hours > 0);
  for (bonus = 10; bonus <= 15; ++bonus) {
    salary = hours * bonus;
  }
  printf("Salary: %d", salary);
}

" How to use a value entered in a do while loop after exiting the do while loop in C? " 在 C 中退出do while do while循环后,如何使用在 do while 循环中输入的值?

If the object the value is assigned to is declared outside the loop, there is no problem of accessing the object outside of the loop.如果赋值给的 object 在循环外声明,则在循环外访问 object 没有问题。

If the object is contrary declared inside the loop only, it has only its lifetime and scope within the loop.如果 object 仅在循环内被相反声明,则它在循环内只有其生命周期和 scope。

But that is not the problem with your code.但这不是您的代码的问题。


" Tried to code it a few times but it's not working for me. " 尝试了几次编码,但它不适合我。

That is not the reason why it does not print the expected output.这不是它不打印预期的 output 的原因。 Beside the mistake of the wrong format specifier at the last printf call:除了最后一次printf调用中错误格式说明符的错误:

printf("Salary: %d", salary);

instead of代替

printf("Salary: %.0f", salary);

or或者

printf("Salary: %d", (int) salary);

because salary is of type float ,因为salary的类型是float

there is nothing syntactically wrong with your code as you can see here , so you might look at the logic behind the algorithm.正如您在此处看到的那样,您的代码在语法上没有任何问题,因此您可以查看算法背后的逻辑。

What you want to do in:你想做什么:

for (bonus = 10; bonus <= 15; ++bonus) {
   salary =hours * bonus;
  }

I mean how your Bonus system works?我的意思是你的奖金系统是如何运作的? you add a bonus to the salary?你在工资上加了奖金? tell me that so I can help you告诉我,这样我可以帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM