【发布时间】:2021-10-10 05:54:09
【问题描述】:
我是一名学生,刚开始编程 4 周,我希望我能在这里获得帮助。所以我正在制作一个程序,您可以将十进制数字转换为八进制和二进制,反之亦然。程序继续要求用户选择,直到他们选择字母 d 退出程序。该程序一开始似乎运行良好,但是当我尝试再次使用相同的字母和输入值时,输出似乎从上次的输出中堆叠,而不是覆盖我猜(对不起,如果我的术语或语法错误,我英语不是很好)我需要改变什么?看不懂呵呵呵呵。
#include<stdio.h>
#include<math.h>
int main(){
int c, k, r=0, e=0, dec=0, o=0, place=1;
long n;
char choice, new, d;
do{
printf("Choices:\na. Decimal to binary and octal\nb. Octal to decimal and binary\nd. Exit.\n\n");
printf("enter your choice:\t");
printf("\n");
scanf(" %c", &choice);
switch(choice){
case 'A':
case 'a':
printf("Conversion: Decimal to binary and octal.\n");
printf("Enter number:\n");
scanf("%ld", &n);
printf("%ld is ", n);
for (c =28; c >= 0; c--){
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf(" in Binary Form. \n");
printf("%ld is ", n);
while (n != 0)
{
o=o+(n%8)*place;
n=n/8;
place=place*10;
}
printf("%ld in Octal Form.\n\n", o);
break;
case 'b':
case 'B':
printf("Conversion: Octal to decimal and binary.\n");
printf("Enter number:\n");
scanf("%ld", &n);
printf("%ld is ", n);
for (c =28; c >= 0; c--)
{
k = n >> c;
if (k & 1)
printf("1");
else
printf("0");
}
printf(" in Binary Form.\n", n, k);
printf("%ld is ", n);
while(n!=0)
{
r=n%10;
dec=dec+r*(pow (8, e));
n=n/10;
e++;
}
printf("%ld in Decimal Form.\n", dec);
default:
printf("Exit.\n\n");
break;
}
}while(choice == 'a'|| choice =='A'|| choice == 'b'|| choice =='B');
return 0;
}
【问题讨论】:
-
请给出准确的输入、预期结果和实际结果。
-
什么是“huehue”?
-
建议:将数字从一个基数转换为另一个基数的实际逻辑移动到另一个函数或 function_s_,而不是全部内联到一个
main. -
k = n >> c但如果long不是 32 位,您将无法始终将移位的long放入int。负值也将是一个问题。如果您只对 ls 感兴趣,这可能并不“重要”。位。 -
你初始化了一堆变量` r=0, e=0, dec=0, o=0, place=1; ` 在顶部,但不在循环中。
标签: c switch-statement do-while