c - 尝试创建一个 C 程序来打印出所有具有有理平方根的数字?

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

void rationalSquareRoots(void);

int main(void) {
    rationalSquareRoots();
}

void rationalSquareRoots(void) {
    for(float i = 0; ; i++) {
    if(sqrt(i) % 1 == 0) {
        printf("%f\n", i);
    }
    sleep(1);
    }
}

我在尝试编写一个程序时遇到了以下问题,该程序打印出所有具有有理平方根的数字(好吧,我猜所有数字都达到溢出点)。

14:19: error: invalid operands to binary expression ('double' and 'int')
    while(sqrt(i) % 1 == 0) {

问题似乎出在 % 运算符上? if 语句不支持它吗?解决方案是什么?

最佳答案

% 运算符仅用于整数之间的除法。

要计算浮点除法的余数,您应该使用 fmod()功能。

使用这个函数,条件应该是fmod(sqrt(i), 1) == 0

https://stackoverflow.com/questions/72914589/

相关文章:

python - 同时从两列中减去值( Pandas , python )

haskell - 在 Haskell 中内存递归函数

windows - 为什么 powershell 说 cl.exe 不被识别?

ios - @Environment dismiss 的存在导致列表在滚动时不断重建其内容

python - Linux 命令行中 Python 对象类的子类

sass - 当我在汇总中使用 scss 时出现意外字符 '@'(请注意,您需要插件才能导入非 Ja

python - 我应该如何打破这个问题的循环?

github-pages - 自定义 GitHub 页面部署说明

python - 为什么这两种计算总和的方法会产生不同的运行时间

mermaid - 使用渲染函数时节点上的事件不调用函数