C:使用scanf进行字符输入
我有一个简单的程序,它将浮点数x提升到整数n的和的幂。我添加了一个while循环,以重复提供适当输入的过程(这里“Y”为yes)。但是,当我在scanf中键入任何字符时(“%c”,anwser);程序失败并关闭。有什么想法吗C:使用scanf进行字符输入,c,character,scanf,C,Character,Scanf,我有一个简单的程序,它将浮点数x提升到整数n的和的幂。我添加了一个while循环,以重复提供适当输入的过程(这里“Y”为yes)。但是,当我在scanf中键入任何字符时(“%c”,anwser);程序失败并关闭。有什么想法吗 float x; char *anwser='Y'; int n,k; while (anwser=='Y'){ printf("Give floating point number x to be raised at the power of n \n ");
float x;
char *anwser='Y';
int n,k;
while (anwser=='Y'){
printf("Give floating point number x to be raised at the power of n \n ");
scanf("%f%d",&x,&n);
printf(" \n result : %f",power(x,n));
printf("\nDo again?? ");
scanf(" %c",anwser);
}
float power(float x , int n){
int i;
float pow=1;
for(i=0;i<n;i++) pow*=x;
return pow;
}
float x;
char*anwser='Y';
int n,k;
while(anwser=='Y'){
printf(“给出浮点数x,以n\n的幂递增”);
scanf(“%f%d”,&x,&n);
printf(“\n结果:%f”,幂(x,n));
printf(“\n请再说一遍”);
scanf(“%c”,anwser);
}
浮动功率(浮动x,整数n){
int i;
浮动功率=1;
对于(i=0;i您不需要char*
来存储像'Y'
这样的字符。
这是您的工作代码,带有一些mod:
#include <stdio.h>
int main(void)
{
double base;
size_t exp;
double res = 1;
char answer;
do {
printf("Give floating point number x to be raised at the power of n: \n");
scanf(" %lf%zu", &base, &exp);
for (size_t i = 0; i < exp; i++) {
res *= base;
}
printf("Result: %lf\n", res);
printf("Do you want repeat? (y/Y or n/N)\n");
scanf(" %c", &answer);
res = 1;
}while (answer == 'Y' || answer == 'y');
return 0;
}
#包括
内部主(空)
{
双基;
尺寸试验;
双res=1;
答案;
做{
printf(“给出以n:\n的幂递增的浮点数x”);
scanf(“%lf%zu”、&base和&exp);
对于(大小i=0;i
'Y'是一个文字常量,这意味着您无法对其进行写入。您可以尝试在scanf中执行此操作。相反,请使用可写字符并将其初始化为'Y'。旁白:除非您的环境处于20世纪,否则请始终使用double
。不幸的是,教科书遗留下来的内容太旧了,早于double
日期。很酷,但有一点解释“为什么”这一方的ion会更好,IMHO。