我正在练习c编程,但我遇到了一个我似乎无法弄清楚的问题.我有一个printf声明,其中包含两个不同int值的标记.无论第一个int是什么,它都会打印0,但第二个int打印正常.这是代码:
#include <stdio.h>
#include <stdlib.h>
int a, temp;
int toBinary();
int toDecimal();
int main()
{
char c;
for(;;)
{
scanf("%d",&a);
scanf(" %c",&c);
switch(c)
{
case 'a' :
printf("%d converted to binary: %d\n",a,toBinary());
break;
case 'b' :
printf("%d converted to decimal: %d\n",a,toDecimal());
break;
case 'c' :
printf("EXIT\n");
return 0;
break;
default :
printf("ERROR c value: %c\n",c);
return 0;
}
}
}
int toBinary()
{
if (a == 0)
return 0;
else
{
temp = a;
a /= 2;
return (temp % 2 + 10 * toBinary());
}
}
int toDecimal()
{
int res=0, base = 1, rem;
while (a > 0)
{
rem = a % 10;
res = res + rem * base;
a /= 10;
base *= 2;
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
问题是printf前两种情况中的语句忽略了实际值int a,但它通常用于两个函数的值.我不确定a在scanf语句中给出了一个值之前有什么问题,我在文本中使用了正确的标记.
由于参数评估的顺序未指定,因此这是未定义的行为.
最简单的解决方法是将副本保存a在不同的变量中,然后打印出来.
int a_copy = a;
printf("%d converted to binary: %d\n",a_copy,toBinary());
Run Code Online (Sandbox Code Playgroud)
但是如果函数首先不使用全局变量会更好.
int toBinary(int a)
{
if (a == 0)
return 0;
else
{
return (a % 2 + 10 * toBinary(a / 2));
}
}
Run Code Online (Sandbox Code Playgroud)
然后你会做:
printf("%d converted to binary %d"\n, a, toBinary(a));
Run Code Online (Sandbox Code Playgroud)