【发布时间】:2021-10-09 06:49:00
【问题描述】:
我写的这两个代码应该输出一样的东西,但是我不知道为什么,当我用Function写的时候,我必须放一个totalDays[0] - = 1; 在第 13 行,当我使用 Class 来编写它时,它就像我想要的那样工作。 (这个问题只出现在 vscode 上,当我使用 Dev c++ 时,没有第 13 行就可以正常工作)
Sample input:
20101010
20101015
First code output: 4 (without line 13)
Second code output: 5 (correct output)
第一个代码:
#include <iostream>
using namespace std;
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int countDays(int d[], int m[], int y[]) {
int totalDays[2];
for (int i = 0; i < 2; i++) {
totalDays[i] += d[i] + 365 * y[i];
for (int j = 0; j < m[i] - 1; j++)
totalDays[i] += monthDays[j];
}
totalDays[0] -= 1;
if (totalDays[0] > totalDays[1]) {
return totalDays[0] - totalDays[1];
} else {
return totalDays[1] - totalDays[0];
}
}
int main() {
int d[2], m[2], y[2], yyyymmdd;
for(int i = 0; i < 2; i++){
cin >> yyyymmdd;
d[i] = yyyymmdd % 100;
m[i] = (yyyymmdd / 100) % 100;
y[i] = yyyymmdd / 10000;
}
cout << countDays(d, m, y);
return 0;
}
第二个代码:
#include <iostream>
using namespace std;
class Solution {
public:
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int countDays(int d[], int m[], int y[], int totalDays[]) {
for (int i = 0; i < 2; i++) {
totalDays[i] += d[i] + 365 * y[i];
for (int j = 0; j < m[i] - 1; j++)
totalDays[i] += monthDays[j];
}
if (totalDays[0] > totalDays[1]) {
return totalDays[0] - totalDays[1];
} else {
return totalDays[1] - totalDays[0];
}
}
};
int main() {
int d[2], m[2], y[2], yyyymmdd, totalDays[2];
for(int i = 0; i < 2; i++){
cin >> yyyymmdd;
d[i] = yyyymmdd % 100;
m[i] = (yyyymmdd / 100) % 100;
y[i] = yyyymmdd / 10000;
totalDays[i] = 0;
}
Solution ob;
cout << ob.countDays(d, m, y, totalDays);
return 0;
}
【问题讨论】:
-
Afaik,c 局部变量可能会或可能不会自动初始化,具体取决于编译器和编译器选项。您正在定义“totalDays”而不将其设置为任何内容,因此您很有可能在那里获得随机数据,然后进行比较。
-
您的代码表现出未定义行为。当
totalDays[i] += d[i] + 365 * y[i];被调用时,int totalDays[2];是一个 未初始化 数组。至少做int totalDays[2] = {0};也编译启用-Wshadow,你在main()和你的第二个例子中的函数之间隐藏数组totalDays。在第二种情况下为参数totalDays选择一个新名称。