ios - 在Objective C中创建负数数组
问题描述
我创建了一个由正数、负数和零数组成的数组,但它将数组中的所有元素都视为正数。在代码中,positiveCount 是 6。如何在 Objective-C 中将负数放入数组中?
NSInteger positiveCount = 0;
NSInteger zeroCount = 0;
NSInteger negativeCount = 0;
NSArray *arr = [NSArray arrayWithObjects:@-4,@-3,@-9,@0,@4,@1, nil];
for (NSInteger i = 0; i < arr.count; i++){
NSLog(@"%d",arr[i]);
if (arr[i] > 0)
{
positiveCount += 1;
} else if (arr[i] < 0){
negativeCount += 1;
} else {
zeroCount += 1;
}
}
NSLog(@"%d",positiveCount);
解决方案
数组中的元素不是数字,它们是NSNumber
实例,即指针。指针总是积极的:
for (NSNumber* number in arr) {
NSInteger intValue = number.integerValue;
NSLog(@"%d", intValue);
if (intValue > 0) {
positiveCount += 1;
} else if (intValue < 0) {
negativeCount += 1;
} else {
zeroCount += 1;
}
}
推荐阅读
- java - 在 Java 和 JavaFX 中创建二维 ArrayList 时出现 NullPointerException
- asp.net-core - 在 Asp.net Core 2 Identity 中更新密码
- c++ - 设置矩阵 zreos :free(): 无效的下一个大小(快速):0x00000000029c21d0
- php - JSTree:使用 php 和 mysql 创建可扩展的树结构
- c++ - 在 C++ 中为 Windows 编写两因素身份验证器?
- jquery - 禁用 UIKIT 3 文件上传 ajax 请求
- scala - 使用 Circe 将字段添加到 json
- sql - 使用包含所有列的索引是否正确?
- java - java中的静态最终(渴望)单例线程是否安全?
- sharepoint - 如何使用 Powerapps for Sharepoint