为什么我们不能为float和double类型的操作数使用operator%? [英] Why we can't use operator % for float and double type operands?
问题描述
我是新来的C / C ++,所以我有一对夫妇约一个基本类型的问题:
-
我已阅读的地方,操作员%不能用于float或double类型的操作数。
然后,我怎么能检查float或double类型变量的整除?我已经表明我的程序下面的错误:的#include<&stdio.h中GT;诠释的main()
{
双N,K,T,I;
INT J = 0;
scanf函数(%F%F,&安培; N,放大器; K);
I = 0;
而(I< N)
{
scanf函数(%F,& T公司);
如果(T%K == 0)/ *错误:无效的操作数为二进制%* /
J ++;
我++;
}
的printf(%D,J);
返回0;
} -
如果一个正整数的射程可达10 ^ 9,我应该使用哪种预选赛或如何实现这样一个大的范围是多少?
下面是对 FMOD
答案一个选择 - 这回答您最初问(因为你是使用双击
键入。如果像从您的意见明确,你真的想使用的整数类型而已,你可以重写你的code如下(与无符号长long int类型
键入给你充足的余量):
的#include<&stdio.h中GT;诠释的main(){ 无符号长长整型N,K,T,I,J = 0; 输出(进入尝试的数目:);
scanf函数(%LLU,&安培; N); 的printf(\\ n输入因素:);
scanf函数(%LLU,&安培; K); I = 0;
而(I< N)
{
的printf(\\ n输入数量测试:);
scanf函数(%LLU,& T公司);
如果(T%K == 0)
J ++;
我++;
}
的printf(发现倍数的数量%LLU \\ n,J);
返回0;
}
请注意我试图使I / O多一点的描述 - 它是提示用户,而不是仅仅有一个闪烁的光标等着他是个好主意。很显然,我猜在提示一点(甚至可能不是你想要使用的语言......)
I am new to C/C++, so I have a couple of questions about a basic type:
I have read somewhere that the operator % can't be applied to float or double type operands. Then how can I check the divisibility of float or double type variables? I have shown my program with error below:
#include <stdio.h> int main() { double n,k,t,i; int j=0; scanf("%f %f",&n,&k); i=0; while(i<n) { scanf("%f",&t); if(t%k==0) /* error:invalid operands to binary % */ j++; i++; } printf("%d",j); return 0; }
If a positive integer has a range up to 10^9, which qualifier should I use or how to achieve such a large range?
Here is an alternative to the fmod
answers - which answer the question you originally asked (since you were using double
type. If, as is clear from your comments, you actually want to use integer types only, you can rewrite your code as follows (with the unsigned long long int
type to give you plenty of headroom):
#include <stdio.h>
int main()
{
unsigned long long int n, k, t, i, j=0;
printf("enter the number of attempts: ");
scanf("%llu", &n);
printf("\nEnter the factor: ");
scanf("%llu", &k);
i=0;
while(i<n)
{
printf("\nEnter the number to test: ");
scanf("%llu",&t);
if(t%k==0)
j++;
i++;
}
printf("The number of multiples found was %llu\n", j);
return 0;
}
Note I have attempted to make the I/O a little more descriptive - it is a good idea to prompt the user, rather than just have a blinking cursor waiting for him. Obviously I am guessing at the prompts a bit (may not even be the language you want to use...)
这篇关于为什么我们不能为float和double类型的操作数使用operator%?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!