我是编程初学者,正在学习 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);
}
我预计如果我输入 num=67 然后对于
您正在循环中更改
num
,因此在第一次迭代后 num
为零。
一个简单的修复:
do
{
int saved_num = num;
....
Your current code
....
num = saved_num;
}
while (choice<=3);