为什么输出在一次循环后返回零

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

我是编程初学者,正在学习 C。我被分配了一个任务来创建一个菜单驱动程序,其中包含以下菜单:反转数字、数字总和、第一个数字和最后一个数字的总和。程序执行没有错误,但第二次运行后输出返回零


**我的代码是:**

#include<stdio.h>
void main()
{
  int num, temp, rev, rem, sum, i, choice, last, first, yes_or_no;
  printf("Enter the number: ");
  scanf("%d", &num);
  do
  {
      printf("\nMenu");
      printf("\n1.Reverse a number.\n2.Sum of digits of a number.\n3.Sum of first and last numbers.");
      printf("\nEnter your choice: ");
      scanf("%d", &choice);
      switch (choice)
      {
      case 1:
         //Reverse the given number
         temp=num;
         rev=0;
         while (num>0)
         {
           rem=num%10;
           rev=rev*10+rem;
           num=num/10;
         }
         printf("\nThe reverse of %d is %d", temp, rev);
         break;
      case 2:
         //Sum of digits of a number
         temp=num;
         sum=0;
         while (num>0)
         {
           rem=num%10;
           sum=sum+rem;
           num=num/10;
         }
         printf("\nThe sum of digits of %d is %d", temp, sum);
         break;
      case 3:
         //Sum of first and last number
         temp=num;
         last=num%10;
         while(num>=10)
         {
           num=num/10;
         }
         first=num;
         sum=first+last;
         printf("\nThe sum of first and last digit of %d is %d", temp, sum);
         break;
      default:
         printf("\nOption does not exist");
         break;
      }
   } 
   while (choice<=3);  
}

这是我的输出的屏幕截图 Screenshot1 screenshot2 为什么会出现这样的情况???

我预计如果我输入 num=67 然后对于

  • 第一种情况返回 76,
  • 第二种情况返回 13,
  • 第三种情况也是13
c menu
1个回答
0
投票

您正在循环中更改

num
,因此在第一次迭代后
num
为零。

一个简单的修复:

  do
  {
      int saved_num = num;

      ....
      Your current code
      ....

      num = saved_num;
  } 
  while (choice<=3); 
© www.soinside.com 2019 - 2024. All rights reserved.