简体   繁体   English

返回带结构的函数时,为什么会出现计算错误?

[英]Why is there a computation error when returning function with structure

I am trying to find the number of elapsed days between two dates. 我想找到两个日期之间经过的天数。 However, with some dates the program prints the wrong number of days between 2 dates. 但是,对于某些日期,程序会在两个日期之间打印错误的天数。

The formula for number of elapsed days is: N=1461 xf(year,month) / 4+ 153 xg(month)/5 +day 经过天数的公式为:N = 1461 xf(年,月)/ 4 + 153 xg(月)/ 5 +天

In my program, I have f and g defined as functions that return different values of years and months depending on what the user inputs. 在我的程序中,我将f和g定义为函数,根据用户输入的内容返回不同的年和月值。

The main problem probably lies with how I scanned the user input with the local variables in the date structure. 主要问题可能在于我如何使用日期结构中的局部变量扫描用户输入。

N1 is the number of elapsed days for the 1st date. N1是第1个日期的经过天数。 N2 is for the second date. N2是第二次约会。

Below is my written code: 以下是我的书面代码:

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
struct date {
        int month;
        int day;
        int year;
    };

int f( int theyear,  int themonth){
    if (themonth <=2)
        theyear = theyear-1;
    else
        theyear =theyear; 
    return theyear;
}

int g( int Month){
    if (Month<=2)
        Month=Month+13;
    else 
        Month = Month+1;

    return Month;
}

int main()

{

    struct date time1, time2;
    int N1; int N2;



    printf("Enter time1 (mm,dd,yyyy): ");
    scanf("%i%i%i", &time1.month, &time1.day, &time1.year);

    printf("Enter time2 (mm,dd,yyyy): ");
    scanf("%i%i%i", &time2.month, &time2.day, &time2.year);
    N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time2.month) / 5 +3;
    N2 = 1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 +21;



    printf("%d \n",abs(N1 -N2));

    return 0;

}

Thank you very much. 非常感谢你。 :) :)

Sample input/output: 样本输入/输出:

Enter time1 (mm,dd,yyyy): 04 10 1994 Enter time2 (mm,dd,yyyy): 03 10 1994 18 输入time1(mm,dd,yyyy):04 10 1994输入time2(mm,dd,yyyy):03 10 1994 18

As you can see, it prints out 18. However, it is supposed to be the number of days in a month. 正如您所看到的,它打印出18个。但是,它应该是一个月内的天数。

change 更改

N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time2.month) / 5 +3;
N2 =1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 +21;

to

N1=1461 * f(time1.year,time1.month) / 4 + 153 * g(time1.month) / 5 + time1.day;
N2 =1461 * f(time2.year,time2.month)/4 +153 * g(time2.month)/5 + time2.day;

?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM