我正在开展一个使用国家气象服务数据的项目。一个应用程序是确定它是白天还是晚上(来自数据 - 而不是来自用户的位置)
我的问题是:我无法理解为什么我写的代码总是返回它是晚上!
我有一个属性:
BOOL isNight;
还有一些变数:
int sunriseDifference
int sunsetDifference
表示气象站的观测时间与该气象站的当地日落或日出之间的差异。
我的逻辑是这样的:
sunriseDifference> 0和sunsetDifference> 0然后是晚上(PM夜晚)
OR
sunriseDifference< 0和sunsetDifference< 0然后是晚上(上午晚上)
否则,就是白天。
以下是代码:
if ((sunriseDifference >= 0) && (sunsetDifference >= 0)) {
self.isNight = YES;
} else if ((sunriseDifference <= 0) && (sunsetDifference <= 0)) {
self.isNight = YES;
} else self.isNight = NO;
这总是产生
self.isNight = YES
我的错误是什么想法?
修改
为了清楚起见,sunriseDifference和sunsetDifference是int表示自日落或日出以来的分钟数。
所以在1500年,在加利福尼亚的一个气象站(白天),变量的值是:
sunriseDifference = 482
sunsetDifference = -118
所以,根据我的逻辑,上面的条件都不满足,因此self.isNight应该是NO。我的代码返回self.isNight为YES ...
我总结说我在代码中犯了一个错误,而不是我的逻辑错误。有什么想法吗?
答案 0 :(得分:1)
同意这些意见,即如果没有天气服务的语义,这个问题很难理解。但如果我正在设计气象服务,这两个参数总会有不同的标志:
sunriseDifference > 0 && sunsetDifference < 0 means it's day
sunriseDifference < 0 && sunsetDifference > 0 means it's night
如果我对数据的含义是对的,那么代码可以更正并简化为:
self.isNight = sunriseDifference < 0 && sunsetDifference >= 0;