嵌套 If 的 C 代码 For 循环;模数和 sqrt 问题

标签 c if-statement nested-loops modulus sqrt

所以,我正在尝试让这个 C 代码工作。它编译,但产生不正确的输出。它应该列出 1 和选定值之间的所有完美平方数。 它做错了什么,经过大量试验和错误后,我认为问题出在模数运算上......比如它提前截断或做一些其他奇怪的事情。

// C Code


/*This program will identify all square numbers between one and a chosen integer*/

#include <stdio.h>
#include <math.h>

int main(){

int i, upper, square_int;
float square;
printf("This program will identify all square numbers between one and a chosen integer");

printf("Please enter the upper limit integer:");
scanf("%d", &upper);

upper = 13; /*scanf is the primary integer input method; this is here just to test it on codepad*/

for (i = 1; i<= upper; ++i) /*i want to run through all integers between 1 and the value of upper*/
{ 
    square = sqrt(i);  /* calc square root for each value of i */
    square_int = square;  /* change the root from float to int type*/

    if (i % (int)square_int == 0) /*check if i divided by root leaves no remainder*/
        printf("%d\n", i);  /*print 'em*/
}
printf("This completes the list of perfect squares between 1 and %d",upper);

return 0; /*End program*/
}

键盘上的输出是:

This program will identify all square numbers between one and a chosen integerPlease enter the upper limit integer:1
2
3
4
6
8
9
12
This completes the list of perfect squares between 1 and 13

这当然是错误的。我希望得到 1、2、4 和 9。谁能指出我在这里搞砸了?

最佳答案

这里有一个更简单的算法

int i = 1;
while (i*i < upper)
{
    printf("%d\n", i*i);
    ++i;
}

另一种方法是计算平方根,将其转换为 int,然后比较数字。

for (i = 1; i <= upper; ++i)
{
    square = sqrt(i);
    square_int = square;
    if (square == (float)square_int)
        printf("%d\n", i );
}

关于嵌套 If 的 C 代码 For 循环;模数和 sqrt 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283657/

相关文章:

c - 初始化指向 NULL 的指针数组

c - 两遍 C 预处理?

二维数组 `memset` 上的困惑和 `free` 上的错误

javascript - 如何将 if 语句添加到对象 block

python - 对任意数量的叠瓦级别进行编码的更优雅的方法

c - 从文件中读取c

c++ - 对于所有编译器,C++ 中的 If 语句中的各种条件是否总是具有相同的执行顺序?

javascript - Javascript 中 boolean 语句是如何计算的

c++ - C++矩阵* vector 乘法中的错误

javascript - 如何打破 JavaScript 中的嵌套循环?