简体   繁体   English

运算顺序int(4 * x / y)与int(x /(y / 4))

[英]Order of operation int(4*x/y) vs int(x/(y/4))

Suppose x and y are of type int. 假设x和y的类型为int。

Are the two expressions: 是两个表达式:

int(4*x/y)

and: 和:

int(x/(y/4))

always evaluate to the same for all x and y of type int ? 始终对int类型的所有xy求值相同? They should mathematically, but only the second expression is consistent (ie, producing the expected value) in a program I've written. 它们在数学上应该是正确的,但是在我编写的程序中,只有第二个表达式是一致的(即产生期望值)。

In many programming languages, 4*x/y and x/(y/4) are different because y/4 , an integer, is the truncated result of the division of y by 4 . 在许多编程语言中, 4*x/yx/(y/4)是不同的,因为整数y/4y除以4的截断结果。 No such truncation exists in 4*x/y . 4*x/y不存在这样的截断。 On obvious difference in when y is 1 , in which case the second expression divides by zero, whereas the first one computes 4*x . y1时存在明显差异,在这种情况下,第二个表达式除以零,而第一个表达式计算4*x

i assume x and y are ints 我假设x和y是整数

then of course not :) on integers: x/4=floor(x/4) mathematically 那么当然不是:)在整数上:x / 4 = floor(x / 4)数学上

which gives you: 这给你:

floor(4*x/y) and floor(x/floor(y/4)) 地板(4 * x / y)和地板(x /地板(y / 4))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 int x{ y = 5 } 可能? - Why is int x{ y = 5 } possible? int x; int y; int * ptr; 是不是初始化,对吧? - int x; int y; int *ptr; is not initialization, right? QTreeWidget childAt(int x,int y)返回NULL - QTreeWidget childAt(int x, int y) returns NULL 如何使用函数 gotoxy(int x, int y) - How to use function gotoxy(int x, int y) 为什么是((unsigned int)x)* y ==((unsigned int)(x * y)总是如此? - why is ((unsigned int)x) * y == ((unsigned int)(x * y) always true? (C ++内存管理)如果我们有一个int x = 1234,而int&y = x ...那么堆栈中y的地址是多少? - (C++ memory management) If we have an int x = 1234, and int &y = x… then what is the address of y on the stack? 访问模板类A中的X和Y,如模板<template <int X,int Y> class> class A; - Accessing X and Y in template class A like in template<template<int X, int Y> class> class A; 在MACRO(X)(Y)中翻转X和Y的顺序 - Flip the order of X and Y in MACRO(X)(Y) string x和int y作为函数的参数 - 不能使用if(x.length() - string x and int y as parameters of function- Cannot use if (x.length()<y) inside the function? C ++ 11 int x,int y之间的随机数,不包括列表<int> - C++11 Random between int x, int y, excluding list<int>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM