本文介绍了在scanf或printf中声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

int main ()
{
	int c,n,fact = 1;
	printf("Enter a number to calculate it's factorial\n");
	scanf("%d", &n);
	for (c=1; c <= n; c++);
	fact = fact *c;
	printf("The factorial of %d	= %d", n, fact);

	printf("Do you want to continue?\n");
	scanf("%c", &(char){ch} );
	if (ch == 'y' || ch == 'Y')
	continue;
	else
	break;
	return(0);

}





在上面的程序中,我已经在scanf中将ch声明为char但是它无效任何一个帮助。



In the above program I have declared ch as char within scanf but it is not working can any one help.

推荐答案


scanf("%c", &(char){ch} );
if (ch == 'y' || ch == 'Y')
   continue;

这不会声明任何东西 - 如果它(它不能,C语法不允许),它就不会在逻辑上可以在scanf调用之外使用。所以后续的行无论如何都无法访问它。

循环的末尾的分号也无济于事...

试试这个:

That doesn't "declare" anything - and if it did (which it can't, it's not allowed by the C syntax), it wouldn't logically be available outside the call to scanf. So the subsequent line wouldn't be able to access it anyway.
And the semicolon at the end of the for loop doesn't help either...
Try this instead:

int main ()
{
    int c,n,fact = 1;
    char ch[100];
    printf("Enter a number to calculate it's factorial\n");
...
    scanf("%c", ch );
    if (ch[0] == 'y' || ch[0] == 'Y')
    {
        continue;
    }
    else
    {
        break;
    }
    return(0);
}

除了你需要循环大部分的 continue / break 逻辑工作!

Except you'll need a loop round most of it for the continue / break logic to work!


#include<stdio.h>

int main ()
{
	int c,n,fact = 1;
	char ch;
	do
	{
		printf("Enter a number to calculate it's factorial\n");
		while (scanf("%d", &n) != 1)
		{
			printf("please try again\n");
			fflush(stdin);
		}
		fflush(stdin);
		for (c=1; c <= n; c++)
		{
			fact = fact * c;
		}

		printf("The factorial of %d	is %d\n", n, fact);

		printf("Do you want to continue?\n");
		scanf("%c", &ch);
	}  while (ch == 'Y' || ch == 'y');
	return 0;
}


这篇关于在scanf或printf中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 23:50
查看更多