【问题标题】:Why does my program not add numbers until -1 is given?为什么我的程序在给出 -1 之前不添加数字?
【发布时间】:2020-03-08 16:20:28
【问题描述】:

以下代码应提示用户输入价格并将其添加到总数中。如果用户输入-1,则添加循环必须终止并且程序应该打印一个总数并退出。但由于某种原因,这并没有发生。

#include <stdio.h>
int main()
{
  int price;
  int sum;
  int exit;

  do
  {
    printf(" Enter a price(-1 to exit)");
    scanf("%d", & price);
    sum = sum + price++;

    printf("the sum of prices is % d ", sum);
  }
  while (exit != -1);

  return 0;
}

问:为什么我的程序在给出 -1 之前不加数字?

【问题讨论】:

  • 输入时需要将'exit'赋值为-1。
  • 所以检查价格是否为-1,如果是,则将退出设置为价格(-1)。
  • 你为什么要增加price
  • 你需要将sum初始化为0
  • 为什么还要有一个变量“exit”?读取价格后,如果为-1,则退出循环。

标签: c loops post-increment


【解决方案1】:

您应该使用 if-else 语句来解决它。如下图:

while(price != -1)
{
    printf(" \nEnter a price(-1 to exit)");
    scanf("%d", &price);
    if (price == -1)
    {
      break;
    }
    else{
        sum = sum + price;
        printf(" \ntotal sum till now is %d", sum);
    }
}

【讨论】:

  • 如果你在内部跳出循环,你应该使用while(1)for(;;)
【解决方案2】:

您没有将exit 分配给任何东西。如果您希望用户输入字符串-1,请检查price 是否为-1 并退出循环。如果您打算让用户输入值为 -1 的字符,则使用 fgetc(stdin),并检查该字符是否为 -1。

另外,为了正确计算总和,您不应使用sum = sum + price++; 增加价格。如果这是为了规避价格为 -1 并且您不想从总和中减去的情况,则应检查循环内的 exit 是否为 -1,并使用 break 关键字。

这不是最大的问题,但您应该根据约定格式化您的代码(例如,正确缩进、标识符旁边的操作符地址等)。

【讨论】:

    【解决方案3】:

    你好,现在看看你命名为 int exit 的问题是什么? 但是您只使 exit only int 变量和内存未过滤,因此计算机从其他东西获取内存,它不是-1,您需要将 %d 价格放在诡计中

    int price;
    do
    {
     block_of_command
    }
    While(price!=-1);
    

    或者

    int exit;
    int price
    do
    {
    scanf("%d",&price);
    exit=price;
    }
    while(exit!=-1);
    

    【讨论】:

      【解决方案4】:

      我更新了代码,但我不知道如何在退出前添加所有用户输入的价格。这是我的代码。

      #include<stdio.h>
      int main()
      {
      int price;
      int sum = 0;
      
      while(price != -1)
      {
          printf(" Enter a price(-1 to exit)");
          scanf("%d", & price);
      
      
          if (price == -1)
          {
            sum = sum + price;
            printf(" adds is %d", sum);
            break;
          }
      
         }
      
      
      
        return 0; 
        }
      

      【讨论】:

      • 使用 if-else 来区分这两种情况。 1)添加用户输入 2)打破循环并退出。仅供参考,我在下面的答案中添加了咖啡 sn-p。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      相关资源
      最近更新 更多