从包含整数的单行计算包号

问题描述 投票:0回答:1

我正在尝试将数字列表作为字符串读取,并计算应该有多少个包装。每个包的最大值为50。例如,"20 25 25 39 37 25 20 10 50 8 16 45 32 10 25 -1"的输出应为11,但我得到10。

您能不能查看我的代码?

int main(void) {
  int input = 0;
  int temp = 0;
  int diff = 50;
  int output = 0;

  printf("Input: \n");
  do {
    scanf("%d", &input);
    if (input < diff) {
      diff -= input;

    } else if (diff == 0 || diff == input) {
      diff = 50;
      output++;
    } else {
      diff = 50 - input;
      output++;
    }

  } while (input != -1);

  printf("Output: %d", output);

  return 0;
}
c while-loop scanf
1个回答
0
投票

正如我在注释中提到的,您在循环的开始读入input一次,并在循环的结束将其与-1进行比较,因此-1将得到处理与每个其他input值相同。

最明显的选择是在两个不同的地方读取,一次在循环之前,一次在循环结束时,这样,您将获得一个新的input直接在]之前>循环条件:] >

printf("Input: \n");
scanf("%d", &input);
while(input != -1) {
    // Processing
    scanf("%d", &input);
} 

注意,我还将循环切换到while循环而不是do ... while循环,就像提供的输入[[only

包含-1一样,然后do ... while仍会处理它,从而导致错误的输出。
© www.soinside.com 2019 - 2024. All rights reserved.