gpt4 book ai didi

c - 如何检查除法的结果是否是 C 中的整数?

转载 作者:行者123 更新时间:2023-12-04 09:54:24 25 4
gpt4 key购买 nike

我需要检查数学除法的结果是否为整数。

例如,8/2 = 4
没问题。
但 5/2 = 2.5
应该不行

我尝试了以下方法:

bool isPrime(int num) 
{
/* Checks all the numbers before the given input. If the result of
dividing
the input by one of those numbers is an int, then the input is not a
prime number. */
int i, check;
double result;
for (i=2; i<num; i++) {
result = (double) num / i;
check = (int) result;
if (isdigit(check))
return false;
}
return true;
}

我做噩梦 isdigit以及如何以正确的方式插入参数。我知道它需要一个 int ,但我有一个 double ,所以我真的不能把这些碎片放在一起。

最佳答案

看起来你正在尝试做这样的事情:

result = (double) num / i;
check = (int) result;
if(check == result) {
...

从逻辑上讲,这是正确的。但它在实践中不起作用,因为浮点数没有无限精度。

检查可分性的正确方法是使用模运算符:
if(num % i == 0) {
// Code to run if num / i is an integer

关于c - 如何检查除法的结果是否是 C 中的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61954369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com