#include<iostream> #include<math.h> using namespace std; class Date{ public: Date (int y, int m, int d){ year=y; month=m; day=d; } void display(int& a, int& b, int& c); private: int year; int month; int day; }; void Date::display(int& a, int& b, int& c){ if(day-10>=0 && month-12>=0){ a=year-2019; b=month-12; c=day-10; if(day-10>=0 && month-12<0){ a=year-2019-1; b=month; c=day-10; if(day-10<0 && month-12>=0){ a=year-2019-1; b=month-1; c=day+20; if(day-10<0 && month-12<0){ a=year-2019-1; b=month-1; c=day+20; } } } } } int main(){ int y,m,d,a,b,c; Date p1(y,m,d); cout<<"请输入一个日期:"<<endl; cin>>y>>m>>d; p1.display(a,b,c); cout<<"已经过了"<<a<<"年"<<b<<"月"<<c<<"天"; return 0; }此代码运行错误,请帮忙改正
时间: 2024-02-25 17:53:16 浏览: 99
这段代码的问题在于,在创建 Date 对象 p1 时,使用了未初始化的变量 y、m 和 d,导致程序行为不可预测。
下面是修改后的代码:
```c++
#include<iostream>
#include<math.h>
using namespace std;
class Date {
public:
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}
void display(int& a, int& b, int& c) {
if (day - 10 >= 0 && month - 12 >= 0) {
a = year - 2019;
b = month - 12;
c = day - 10;
if (day - 10 >= 0 && month - 12 < 0) {
a = year - 2019 - 1;
b = month;
c = day - 10;
if (day - 10 < 0 && month - 12 >= 0) {
a = year - 2019 - 1;
b = month - 1;
c = day + 20;
if (day - 10 < 0 && month - 12 < 0) {
a = year - 2019 - 1;
b = month - 1;
c = day + 20;
}
}
}
}
}
private:
int year;
int month;
int day;
};
int main() {
int y, m, d, a, b, c;
cout << "请输入一个日期:" << endl;
cin >> y >> m >> d;
Date p1(y, m, d);
p1.display(a, b, c);
cout << "已经过了" << a << "年" << b << "月" << c << "天";
return 0;
}
```
在修改后的代码中,先接收用户输入的日期,再使用这个日期创建 Date 对象 p1,从而避免了使用未初始化的变量。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)