求帮助。。看看我的思路对不对
从键盘上任意输入两个整数p、r,分别使用while、do-while、for循环,求解p的r次方,并输出显示结果。#include <stdio.h>
int main() {
int p, r;
int result;
int tmp;
puts("输入整数:p>0, r>0,求解p^r");
scanf("%d%d",&p,&r);
tmp = r;
result = 1;
while( tmp ) {
result *= p;
--tmp;
}
printf("用while求p^r=%d\n", result);
tmp = r;
result = 1;
do {
result *= p;
--tmp;
}while(tmp);
printf("用do while求p^r=%d\n", result);
tmp = r;
result = 1;
for(tmp=r,result=1; tmp; --tmp) {
result *= p;
}
printf("用for求p^r=%d\n", result);
} pow(p, r) //这个是求次方的函数 do while 不行
应为do while 是先执行了在判断 如果是一次就不用执行任何代码 应该有说过 while 和 for 是可以等价转换的
但 do while 不行#include<stdio.h>
int main()
{
double p,t;
int r,i;
char ch;
s: printf("Please Input r:");
scanf_s("%d",&r);
printf("Please Input p:");
scanf_s("%lf",&p);
t = p;
for (i = 1; i < r; i++)
{
t *= p;
}
printf("%lf ^ %d == %lf\n",p,r,t);
while ((ch = getchar())!= '\n');
goto s;
return 0;
}#include<stdio.h>
int main()
{
double p,t;
int r,i;
char ch;
s: printf("Please Input r:");
scanf_s("%d",&r);
printf("Please Input p:");
scanf_s("%lf",&p);
t = p;
i = 1;
while (i<r)
{
t *= p;
i++;
}
printf("%lf ^ %d == %lf\n",p,r,t);
while ((ch = getchar())!= '\n');
goto s;
return 0;
}
页:
[1]