我想知道如何检查我输入的日期是否有效。
public static bool JeVeljavenDatum(int dan, int mesec, int leto)
{
return dan > 0 && dan <= 31 && mesec > 0 && mesec <= 12 && leto > 0 && leto <= DateTime.Today.Year;
}
如上所示,我并不认为该功能是检查日期的最佳方法,因此欢迎您提出任何提示:)
问题在于检查年份是否为leap年,以及月份是否只有30天或31。 或者是使用long if方法检查这种情况的唯一方法。
if ((Mesec == 1 || Mesec == 3 || Mesec == 5 || Mesec == 7 || Mesec == 8 || Mesec == 10 || Mesec == 12) && Dan == 31)
{
Dan = 1;
Mesec++;
if (Mesec == 12)
{
Mesec = 1;
Leto++;
}
}
if ((Mesec == 4 || Mesec == 6 || Mesec == 9 || Mesec == 11) && Dan == 30)
{
Dan = 1;
Mesec++;
if (Mesec == 12)
{
Mesec = 1;
Leto++;
}
}
答案 0 :(得分:0)
尝试使用检查数字的constructor创建正确的DateTime。
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int validate (int c, string v[]); //prototpe validate function
int main (int argc, string argv[])
{
int validate (int argc, string argv[]); //run validate for argc and argv
printf("Key is valid\n"); //if valid, print message
}
int validate (int c, string v[])
{
//Validate that only one Command Line Argument was entered
if (c != 2) //Check the number if entered commands at execution
{
//If more than one, print error message
printf("Key must be the only Command Line Argument\n");
return 1; //Return false
}
//Validate that Key length is 26 characters
if (strlen(v[1]) != 26) //Don't forget null 0
{
printf("Key must contain exactly 26 characters\n");
return 1; //Return false
}
//Validate that all Key characters are alphabetic
for (int i = 0, n = strlen(v[1]); i < n; i++)
{
//Check each element of the array
if (isalpha(v[1][i]))
{
continue; //Continue if alphabetic
}
else
{
//if non-alphabetic, print error code
printf("Key must contain only alphabetic characters\n");
return 1; //Return false
}
}
//Validate that each Key character is unique
for (int x = 0, z = strlen(v[1]) - 1; x < z; x++)
{
//Create a second loop to compare every element to the first before incrementing the first
for (int y = x + 1; y < z; y++)
{
//Cast array elements to int, check if each element equals next element in array
if (v[1][x] == v[1][y])
{
printf("Key must contain exactly 26 unique characters\n");
return 1;
}
}
}
return 0; //Key is valid, so return true
}