我有一个简单的程序,它将浮点数x提升到整数n的幂和。我添加了一个while循环来重复提供适当输入的过程(这里' Y'同意)。但是,当我在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 ");
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;
}
答案 0 :(得分:2)
您不需要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;
}