If语句未被求值C++

If statement not being evaluated C++

本文关键字:C++ 语句 If      更新时间:2023-10-16

我正在编写一个函数来返回两个日期之间的差异。因此,对于yearDifference语句(请参阅代码中的断点注释(,我将从另一个语句中减去一个,然后使用if语句检查结果是否为负数。

if语句没有得到评估,是什么原因导致了这种情况?

我在visualstudio中使用了一个断点来逐行检查它,并且它不会在if语句上停止以进行检查

int UUDate::Between(UUDate date) {
//TODO - Add your implementation here
int daycount = 0;
int tempMonth = date.month_;
int tempDay = date.day_;
int yearDifference;
while (month_ != tempMonth)
{
if (month_ == 1 || month_ == 3 || month_ == 5 || month_ == 7 || month_ == 8 || month_ == 10 || month_ == 12) {
daycount += 31;
}
else if (month_ != 2) {
daycount += 30;
}
else {
if (year_ % 4 == 0) {
daycount += 29;
}
else {
daycount += 28;
}
}
tempMonth++;
if (tempMonth > 12)
tempMonth = 1;
}
yearDifference = year_ - date.year_; //breakpoint here
if (yearDifference < 0) { //skipped
yearDifference * -1;
}
if (day_ - tempDay < 0) {
return ((day_ - tempDay) * 1) + daycount + (yearDifference * 365);
}
else {
return (day_ - tempDay) + daycount + (yearDifference * 365);
}

}

if (yearDifference < 0) { //skipped
yearDifference * -1;
}

此代码没有任何作用。将yearDifference乘以-1并将结果丢弃没有效果。你的意思可能是yearDifference *= -1;,相当于yearDifference = yearDifference * -1;

我发现解决方案是一个简单的错误,我没有意识到它阻止了if语句的评估。在if语句中,我有

yeardifference * -1;

这是一个拼写错误,它应该在星号后面有一个等号,将yearDifference乘以-1,从而将其从负数变为正数。很抱歉,每个人都犯了一个简单的错误,尽管感谢您的帮助:(