C++ 程序的意外行为
我需要根据以'd m yyyy'格式给出的2个输入日期执行以下计算C++ 程序的意外行为,c++,C++,我需要根据以'd m yyyy'格式给出的2个输入日期执行以下计算 1. if year_date1 > year_date2 // output 10000 2. else if month_date1 > month_date2 // output diff_month * 500 3. else if day_date1 > day_date2 // output diff_day * 15 4. else
1. if year_date1 > year_date2 // output 10000
2. else if month_date1 > month_date2 // output diff_month * 500
3. else if day_date1 > day_date2 // output diff_day * 15
4. else // output 0
例如输入- 输出
0
但对于前面提到的同一输入案例,为什么我得到的是“3000”而不是“0”
代码
int main(){
int dif_day,dif_month,dif_year;
int day[2],month[2],year[2];
for(int i = 0; i < 2; i++)
cin >> day[i] >> month[i] >> year[i];
dif_day = day[0] - day[1];
dif_month = month[0] - month[1];
dif_year = year[0] - year[1];
if(dif_year > 0){
cout << 10000;
}
else if(dif_month > 0){
cout << dif_month * 500;
}
else if(dif_day > 0){
cout << dif_day * 15;
}
else
cout << 0;
return 0;
}
int main(){
国际日、国际月、国际年;
整数日[2],月[2],年[2];
对于(int i=0;i<2;i++)
cin>>日[i]>>月[i]>>年[i];
dif_日=日[0]-日[1];
dif_月=月[0]-月[1];
dif_年=年[0]-年[1];
如果(dif_年>0){
cout(0){
cout(0){
您的代码可以减去年
、月
和日期
,并进行适当的计算
在您的示例中,dif_year
是-1
,因此
if(dif_year > 0)
不成立。然后dif\u month
显示为6。下一个条件是
if (dif_month > 0) // dif_month == 6
cout << dif_month*500 // 6*500 = 3000
if(dif\u month>0)//dif\u month==6
coutdif_year不大于0,但是-1,因此程序转到第一个else if语句,其中dif_year大于0(6),并执行6*500,即3000,并输出。其余的else语句被跳过
要获得0,第一个日期的所有数字必须小于第二个日期的数字。例如,1 1014 2 7 1015将为您提供0的输出
程序的行为是非常值得期待的。diff\u month
是6
。因此,您的程序执行cout自动q-ban会受到已关闭问题数量的影响。您的此问题已关闭,因为它没有问题。请编辑它以获得清晰的问题,但不会显示已发布的答案nvalidated。之后,ping我(写一条以@peterh…开头的评论),你就可以进行重新开放投票了(重新开放你的问题需要3次,但你也可以单击“重新开放”来打开你自己的封闭问题)。只有在您修复问题后才能执行此操作,因为编辑或第一次重新开放投票会将您的问题放入重新开放审核队列中,如果最终未获得重新开放投票,则我们需要等待一个月或更长时间才能重新开始此操作。|您的问题看起来是这样的:“我想要这个,这是我的代码,可以吗?”这是离题的,但这样的问题可以:“我想要这个,这是我的最小示例,但它不起作用,因为(解释),问题是什么?”
if (dif_month > 0) // dif_month == 6
cout << dif_month*500 // 6*500 = 3000