我只想问你是怎么决定的
Enter a number: 14
Then the date to day is Sunday.
上面的演示是1-7 =星期一 - 星期日然后如果值是8那么它的星期一再次......但我怎么能确定呢?使用循环和模数?...
感谢任何帮助我的评论...
任何语言都可以,我只想知道算法...
答案 0 :(得分:2)
您可以使用模块
模块达到0所以它会像
<?php
$value = 13;
$daynames = array("mon", "tues", "wed", "thur", "fri", "sat", "sun");
// The + 1 is because % is 0, and you want 1-7
echo (($value % 7) + 1) . "day of the week";
echo "the day is " . $daynames[($value % 7)];
?>
答案 1 :(得分:1)
如果您有七天的开关/案例或if / else,您可以使用modulo 7将输入输入到所需的7天范围内。
答案 2 :(得分:1)
您可以使用switch语句和模运算来执行此操作。
学习计算机科学的第一步是要知道数字通常不是从1开始。从0开始。这个想法将在未来对你有很大的帮助!
// accept numbers 0-6. If 7 were to get put in, it would end up being 0 since 7 % 7 = 0.
switch(num % 7) {
case 0: return "Sunday";
case 1: return "Monday";
case 2: return "Tuesday";
/// rest here...
default: throw new IllegalArgumentException();
}
答案 3 :(得分:1)
以模7为数似乎是显而易见的。
答案 4 :(得分:1)
string day;
int inputNumber;
if(inputNumber%7 == 0)
day = "monday"; // or sunday if you prefer :p
else if(inputNumber%7 == 1)
day = tuesday
...
...
...
答案 5 :(得分:1)
在C ++中,int day = (i-1) % 7;
将为您提供从零开始的偏移量。这是示例代码:
#include <iostream>
#include<string>
using namespace std;
int main()
{
static const std::string days [] =
{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
static const size_t num_days = sizeof(days)/sizeof(days[0]);
for( int i = 1; i <= 31; ++i )
{
int day = (i-1) % 7;
cout << day << " = " << days[day] << "\n";
}
}
答案 6 :(得分:1)
获取传入的int值的模7并为其创建switch语句。
switch:
case 1:
Sunday
case 2:
Monday
// and so on
答案 7 :(得分:1)
datArr= new Array ('Sun', 'Mon', 'Tue',Wen', 'Thu, 'Fri', 'Sat');
day =datArr[(daynum%7)];
如果将星期日视为零日,则无需在模数之后减去1。当然,如果遇到零的实际值,大多数解决方案都将失败,零潜水。
答案 8 :(得分:1)
import java.util.Scanner;
public class TestMain {
private static final String[] DAYS = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thusday", "Friday", "Saturday" };
public static void main(final String[] args) {
System.out.print("Enter a number: ");
final Scanner scanner = new Scanner(System.in);
final int n = scanner.nextInt();
System.out.print("Then the date to day is " + DAYS[n % 7]);
}
}