使用嵌套for循环使用C查找数字的二次方
Using nested for loop to find the second power of numbers using C
我需要使用嵌套的 for 循环求从 -14 到 14 的数字的平方。到目前为止,我对应该如何编写外循环感到困惑我只有这个
for(i=14;i>0;i--1)
{
for (k=i;k>=pow(i,2); k--)
}
这仅适用于 0-14。请帮助
I need to find the squares of numbers from -14 to 14 using nested for loops.
我假设这是一个关于嵌套循环的练习,而不是一个数学问题,因此效率低下但预期的解决方案可能如下
#include <stdio.h>
int main(void)
{
for (int i = -14; i <= 14; i++) {
// ^^^ ^^^^^
int square = 0;
// Take the absolute value of the outer index
int factor = i < 0 ? -i : i;
// Remember that i * i = i + i + ... + i (i times)
for (int j = 0; j < factor; ++j) {
// ^ ^^^^^^
square += factor;
}
printf("The square of %d is %d\n", i, square);
}
}
我需要使用嵌套的 for 循环求从 -14 到 14 的数字的平方。到目前为止,我对应该如何编写外循环感到困惑我只有这个
for(i=14;i>0;i--1)
{
for (k=i;k>=pow(i,2); k--)
}
这仅适用于 0-14。请帮助
I need to find the squares of numbers from -14 to 14 using nested for loops.
我假设这是一个关于嵌套循环的练习,而不是一个数学问题,因此效率低下但预期的解决方案可能如下
#include <stdio.h>
int main(void)
{
for (int i = -14; i <= 14; i++) {
// ^^^ ^^^^^
int square = 0;
// Take the absolute value of the outer index
int factor = i < 0 ? -i : i;
// Remember that i * i = i + i + ... + i (i times)
for (int j = 0; j < factor; ++j) {
// ^ ^^^^^^
square += factor;
}
printf("The square of %d is %d\n", i, square);
}
}