gpt4 book ai didi

c - 在 C 中运行以下程序时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:43 25 4
gpt4 key购买 nike

下面的程序是用C写的IDE:代码:: block 16.01

问题:编写一个程序,求出两个日期的年月日之差。日期在有效范围内,第一个日期早于第二个。

 //To find difference of two dates in years,months and dates, Dates are  in valid range and first date falls before second.

#include <stdio.h>
int main()

{
int d,d1,d2,m,m1,m2,y,y1,y2;
printf("Enter first date (dd/mm/yyyy) : ");
scanf("%d/%d/%d,&d1,&m1,&y1");
printf("Enter the second date (dd/mm/yyyy) : ");
scanf("%d/%d/%d,&d2,&m2,&y2");
if(d2<d1)
{
if(m2==3)
{
if (y2%100!=0 && y2%4==0|| y2%400==0) // Checking leap year
d2+=29;
else
d2+=28;

}
else if (m2==5||m2==7||m2==10||m2==12)
d2+=30;
else
d2+=31;

}
if (m2<m1)
{
y2=y2-1;
m2+=12;
}
y=y2-y1;
d=d2-d1;
m=m2-m1;
printf("Difference of the two dates is : ");
printf("%d years,%d months,%d days\n",y,m,d);
return 0;
}

最佳答案

scanf("%d/%d/%d,&d1,&m1,&y1");

scanf("%d/%d/%d,&d2,&m2,&y2");

错了你必须阅读 scanf() 的手册.

第一个参数是格式字符串 "%d/%d/%d"并且您必须在以下位置传递每个地址:&d1, &m1, &y1 .

scanf("%d/%d/%d", &d1, &m1, &y1);
scanf("%d/%d/%d", &d2, &m2, &y2);

你应该验证函数的返回值:

if (scanf("%d/%d/%d", &d1, &m1, &y1) != 3) {
fprintf(stderr, "Something go wrong!");
return 1;
}

关于c - 在 C 中运行以下程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41531885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com