This two code I wrote should output the same thing, but I don't know why, when I use Function to write it, I have to put a totalDays[0] -= 1; in the line 13, and when I use Class to write it, it just works as I intended. (This problem only occurs with vscode, when I use Dev c++, it just works fine without line 13)
Sample input:
20101010
20101015
First code output: 4 (without line 13)
Second code output: 5 (correct output)
First code :
#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;
}
Second code :
#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;
}
int totalDays[2];is an Uninitialized array whentotalDays[i] += d[i] + 365 * y[i];is called. At least doint totalDays[2] = {0};Also compile with-Wshadowenabled, you shadow the arraytotalDaysbetweenmain()and your function in the second example. Choose a new name for the parametertotalDaysin the second case.