2013-10-09 78 views
0
void mul() 
{ 
    int x,y,sum = 0; 
    scanf("%d",&x); 
    scanf("%d",&y); 
    while (x != 0){ 
     if (x%2 != 0) 
      sum = sum + y; 
     x = x/2; 
     y = 2*y; 
    } 
    printf("%d",sum); 
} 

int main() 
{ 
    char c; 
    printf("Enter two numbers and y to exit"); 
    //mul(); 
    scanf("%c",&c); 
    while (c != 'y'){ 
     mul(); 
    } 
    return 0; 
} 

在运行此程序时,它不会在给出输入'y'时退出。为什么?这里是否有逻辑错误?

+0

您将遇到'scanf()'读取整数将为'scanf()'读取要处理的字符的新行。您应该通过打印您读取的数据进行调试,以便了解该程序是否获得了您认为正在获得的输入内容。你也应该测试'scanf()'的返回值;如果您有早期的EOF,您会得到奇怪的行为,或者当您期望数字数据时,会得到非数字数据。 –

回答

2

您没有扫描while循环。这样做:

char c = 'n'; 
while (c != 'y') 
{ 
    printf("Enter two numbers and y to exit"); 
    scanf("%c",&c); 
    mul(); 
} 

只是想指出一些额外的东西,当你输入一个字符像yn,然后按Enter键,字符(你输入的)和一个字符(这是进入按键 - 的换行符)放在输入缓冲区中。第一个字符被scanf消耗,但换行符保留在输入缓冲区中。

解决方案是使用消耗额外的换行符:

scanf(" %c", &c); 
     ^<------------Note the space 
+1

(或者更重要的一点,他不会修改while循环中的'c')。 –

+1

@Acme:并且事先将'char c'初始化为一个虚拟值 – Enigma

+1

'mul()'应该位于'scanf()'之前 – Rohan

0

更好的你做这样

do{ 
    scanf("%c",&c); 
    mul(); 
}while (c != 'y'); 
0

试试这个代码或只需添加“静态INT主”在你的代码。

int Main() 
{ 
    char c; 
    printf("Enter y to exit"); 
    scanf("%c",&c); 
    while (c != 'y') 
    { 
     mul(); 
     } return 0; } 

void mul() { 
printf("Enter two numbers"); 
int x,y,sum = 0; 
scanf("%d",&x); 
scanf("%d",&y); ................ } 
+0

'public static int main'不是C. –

+0

@ YuHao感谢哥们,我没有注意到它。 – Rajeshkumar