请看一下本应该在明天发布的节目。该程序来自教科书,并使用三个功能。 不幸的是,它提供了错误的输出:
Enter today's date (mm dd yyyy): 09 25 1977
Tomorrow's date is 00/10/25.
但有时它确实提供了正确的输出:
Enter today's date (mm dd yyyy): 10 07 2015
Tomorrow's date is 10/08/15.
我不明白为什么会这样。 这是程序:
// Program to determine tomorrow's date
#include <stdio.h>
#include <stdbool.h>
struct date
{
int month;
int day;
int year;
};
int main (void)
{
struct date today1, tomorrow;
struct date tomorrow_date (struct date today);
printf("Enter today's date (mm dd yyyy): ");
scanf("%i%i%i", &today1.month, &today1.day, &today1.year);
tomorrow = tomorrow_date (today1);
printf ("Tomorrow's date is %.2i/%.2i/%.2i.\n", tomorrow.month, tomorrow.day, tomorrow.year % 100);
return 0;
}
// Function to find the number of days in a month
int number_of_days (struct date d)
{
int days;
bool is_leap (struct date d);
const int days_per_month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (is_leap (d) == true && d.month == 2)
days = 29;
else
days = days_per_month[d.month - 1];
return days;
}
// Function to determine if it's a leap year
bool is_leap (struct date d)
{
bool leap_year;
if ( (d.year % 4 == 0 && d.year % 100 != 0) || (d.year % 400 == 0))
leap_year = true;
else
leap_year = false;
return leap_year;
}
// Function to determine tomorrow's date using compound literals
struct date tomorrow_date (struct date today)
{
struct date tomorrow;
int number_of_days(struct date d);
if (today.day != number_of_days(today))
tomorrow = (struct date) {today.month, today.day + 1, today.year};
else if (today.month == 12) // end of year
tomorrow = (struct date) {1, 1, today.year + 1};
else // end of month
tomorrow = (struct date) {today.month + 1, 1, today.year};
return tomorrow;
}
谢谢!
答案 0 :(得分:2)
扫描日期时使用格式说明符0xff
。此说明符读取十进制整数,但接受C代码也接受的表单,即十六进制(0377
)和八进制(08
)。
输入09
和sscanf
被视为八进制,但它们不是合法的八进制数,因为八进制没有数字8或9.扫描在第一个非八进制数字处停止。 (顺便说一句,你不能检查%i
是否返回3.)
补救措施是将%d
格式替换为08
格式,该格式会按照人类读者的预期扫描<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul id="list">
<!-- In here comes the data! -->
</ul>
<button id="button">Get Data</button>
</body>
</html>
。
答案 1 :(得分:0)
通过将输入显示为09,您可以在八进制基础中输入输入。删除月份输入中的前导0。
http://www.cplusplus.com/reference/cstdio/scanf/