【问题标题】:Printing an integer打印一个整数
【发布时间】:2012-03-26 08:37:26
【问题描述】:

我让用户输入一个日期,例如'January 10 12' 表示月、日和年。如果月份是一个两位数的数字,它可以正常工作,但是如果用户输入“1 月 12 日 01”或前面带有 0 的任何数字,如果月份是 01 或“1 月 12 日 0”,我只会得到“1 月 12 日 1” ' 如果月份是 00 而不是我输入的。是否存在某种格式的错误?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef int (*compfn)(const void*, const void*);

struct date
{
    int month;
    int day; //The day of the month (e.g. 18)
    int year; //The year of the date    
};

char* months[]= {
   "January", "February",
   "March", "April",
   "May", "June",
   "July", "August",
   "September", "October",
   "November", "December"};


int getMonth(char tempMonth[])
{
    if(strcmp(tempMonth, months[0]) == 0) return 0;
    if(strcmp(tempMonth, months[1]) == 0) return 1;
    if(strcmp(tempMonth, months[2]) == 0) return 2;
    if(strcmp(tempMonth, months[3]) == 0) return 3;
    if(strcmp(tempMonth, months[4]) == 0) return 4;
    if(strcmp(tempMonth, months[5]) == 0) return 5;
    if(strcmp(tempMonth, months[6]) == 0) return 6;
    if(strcmp(tempMonth, months[7]) == 0) return 7;
    if(strcmp(tempMonth, months[8]) == 0) return 8;
    if(strcmp(tempMonth, months[9]) == 0) return 9;
    if(strcmp(tempMonth, months[10]) == 0) return 10;
    if(strcmp(tempMonth, months[11]) == 0) return 11;
}

int sortDates(struct date *elem1, struct date *elem2)
{
    if ( elem1->year < elem2->year)
        return -1;
    else if ( elem1->year > elem2->year )
        return 1;


    /* here you are sure the years are equal, so go on comparing the months */

    if ( elem1->month < elem2->month )
        return -1;
    else if ( elem1->month > elem2->month )
        return 1; 

    /* here you are sure the months are equal, so go on comparing the days */

    if ( elem1->day < elem2->day )
        return -1;
    else if ( elem1->day > elem2->day )
        return 1; 
    else
        return 0;

}

main()
{
    int n;
    int i;
    char tempMonth[255]; //Used to store the month until checked

    scanf("%d", &n);

    struct date *list;

    list = (struct date *)malloc((n * sizeof(struct date)));

    for(i = 0; i < n; i++)
    {
        scanf("%s %d %d", tempMonth, &list[i].day, &list[i].year);
        list[i].month = getMonth(tempMonth);
    }

    qsort(list, n, sizeof(struct date), (compfn)sortDates);

    for(i = 0; i < n; i++)
    {
        printf("%s %d %d\n", months[list[i].month], list[i].day, list[i].year);
    }

}

【问题讨论】:

  • 为什么不在这里循环:if(strcmp(tempMonth, months[i]) == 0) return i;

标签: c int printf


【解决方案1】:

如果您想始终输出至少两位数字,前面有零,请使用%02d 格式字符串而不是%d

【讨论】:

  • 请注意:用户可以在第一个 scanf 中输入负数(对于 n)。确保您的代码正确处理该问题,以及用户输入的数字是否超过 255。
猜你喜欢
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 2013-06-02
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多