Objective C Math - 几何序列结果

时间:2021-08-05 02:45:37

For my app (OSX, not IOS) i have a geometric sequence (stored in container array) generated like this:

对于我的应用程序(OSX,而​​不是IOS),我有一个生成如下的几何序列(存储在容器数组中):

- (void)initContainerFor:(NSInteger)maxRows
{

self.container = [[NSMutableArray alloc] init];
NSInteger start = [self.firstTextFieldValue integerValue];
NSInteger ratio = [self.secondTextFieldValue integerValue];

// ASCENDING
for (NSInteger i = 1; i < (maxRows +1 ); i++)
{
    NSInteger currentValue = start * pow(ratio,i-1);
    [self.container addObject:currentValue];
}
}

User can enter the "start" and "ratio" integer. I want to give a feedback if limit (MAX_INT) is exceeded. I wrote this function:

用户可以输入“开始”和“比率”整数。如果超出限制(MAX_INT),我想给出反馈。我写了这个函数:

- (BOOL)maxCheck
{

    if ([self.container lastObject] > INT_MAX)
        return false;

    return true;
}

But this seems not to work. If i enter 2 for start and 200 for ratio i have this container content:

但这似乎不起作用。如果我输入2表示开始,200表示比例,我有这个容器内容:

Container: (
    2,
    400,
    80000,
    16000000,
    "-1094967296",
    49872896,
    1384644608,
    2051014656,
    "-2113929216",
    0
)

Please help to understand what i see in the container (strings??) and how to get a correct check for the maximum value.

请帮助理解我在容器中看到的内容(字符串??)以及如何正确检查最大值。

2 个解决方案

#1


0  

You can not compare the value after overflow with INT_MAX, as the overflow already happened. Or put differently, by its very definition and semantics, no integer can be bigger than INT_MAX.

溢出后的值与INT_MAX无法比较,因为溢出已经发生。或者换句话说,通过它的定义和语义,没有整数可以大于INT_MAX。

What you can test is

你可以测试的是什么

[self.container lastObject] > INT_MAX/ratio

to find the sequence element that would cause overflow in the next step.

找到在下一步中会导致溢出的序列元素。

#2


1  

As you can see from log of array, you actually exceed INT_MAX limit twice, when next element become negative. So you can just add check to initContainer: method - if element is less then the previous, INT_MAX limit is reached.

从数组的日志中可以看出,当下一个元素变为负数时,实际上超过了INT_MAX限制两次。因此,您只需将检查添加到initContainer:方法 - 如果element小于先前的INT_MAX限制。

TIP: INT_MAX is a signed value.

提示:INT_MAX是有符号值。

#1


0  

You can not compare the value after overflow with INT_MAX, as the overflow already happened. Or put differently, by its very definition and semantics, no integer can be bigger than INT_MAX.

溢出后的值与INT_MAX无法比较,因为溢出已经发生。或者换句话说,通过它的定义和语义,没有整数可以大于INT_MAX。

What you can test is

你可以测试的是什么

[self.container lastObject] > INT_MAX/ratio

to find the sequence element that would cause overflow in the next step.

找到在下一步中会导致溢出的序列元素。

#2


1  

As you can see from log of array, you actually exceed INT_MAX limit twice, when next element become negative. So you can just add check to initContainer: method - if element is less then the previous, INT_MAX limit is reached.

从数组的日志中可以看出,当下一个元素变为负数时,实际上超过了INT_MAX限制两次。因此,您只需将检查添加到initContainer:方法 - 如果element小于先前的INT_MAX限制。

TIP: INT_MAX is a signed value.

提示:INT_MAX是有符号值。