[英]program for calculating x raised to the power of y using while loop
int main()
{ unsigned int x, y;
printf_s("Enter value for x: ");
scanf_s("%u", &x);
printf_s("Enter value for y: ");
scanf_s("%u", &y);
unsigned int count = 1;
while (count < y);
{
x *= x;
count++;
}
printf_s("x raised to the power of y is: %u", x);
}
Hi, I'm not sure where I went wrong.嗨,我不确定我哪里出错了。 When I run it, I enter two values as prompted and then nothing else happens.当我运行它时,我按照提示输入两个值,然后没有其他反应。 It just stops after I enter they value for y.它只是在我输入它们的 y 值后停止。
Enter value for x: 3 Enter value for y: 2为 x 输入值:3 为 y 输入值:2
Like this.像这样。 Could someone point me in the right direction?有人能指出我正确的方向吗? I understand that this way will not work if y <= 1. But shouldn't it work for when y > 1?我知道如果 y <= 1,这种方式将不起作用。但是当 y > 1 时它不应该起作用吗?
I've searched for it.我已经搜索过了。 There is another question using for loop.使用 for 循环还有另一个问题。 I can see that it could be done with for loop but I think while loop is more appropriate since it gives more freedom.我可以看到它可以用 for 循环来完成,但我认为 while 循环更合适,因为它提供了更多的自由。 Please and thank you!谢谢,麻烦您了!
;
你有;
past the while
and your code in braces is not executed in the loop过去while
,大括号中的代码不会在循环中执行x *= x
is definitely wrong. x *= x
绝对是错误的。unsigned long long mypow(unsigned x, unsigned y)
{
unsigned long long result = 1;
while(y--) result *= x;
return result;
}
int main(void)
{
unsigned x, y;
scanf("%u,%u", &x, &y);
printf("%u ^ %u = %llu\n", x, y, mypow(x, y));
}
https://godbolt.org/z/xzx8Mo5aW https://godbolt.org/z/xzx8Mo5aW
#include <iostream>
int main()
{
unsigned int long x; // assign x
printf_s("Enter value for x: "); // prompt
scanf_s("%u", &x); // read input
unsigned int y; // assign y
printf_s("Enter value for y: "); // prompt
scanf_s("%u", &y); // read input
unsigned int count = 0; // initialize count
unsigned int power = 1; // initialize power
while (count < y) // loop while y is less than count
{
power *= x; // multiply power by x
count++; // increment count
} // loop ends
printf_s("x raised to the power of y is: %u", power); // display result
}
I've deleted ;.我已经删除了;。 I've added long to unsigned int.我在 unsigned int 中添加了 long。 I've set up a new variable, power, in order to contain the value of x raised to a power of y.我设置了一个新变量 power,以包含 x 的 y 次幂的值。 I've checked if this works when y = 0 or 1 and it does.我已经检查了这在 y = 0 或 1 时是否有效,并且确实有效。 Thank you everyone for your help!谢谢你们每一个人的帮助!
PS Textbook answer has pritnf( "%s", "Enter first integer: "); PS教科书答案有 pritnf( "%s", "Enter first integer: "); for prompting for the first integer, x.用于提示输入第一个整数 x。 I'm not sure why they add %s as it works perfectly fine without it.我不确定他们为什么要添加 %s,因为没有它就可以正常工作。 Does anyone know why one would add %s?有谁知道为什么要添加 %s?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.