根据用户输入生成年、月、周和日

Generating Year, Months, Weeks and Days from user input

本文关键字:用户 输入      更新时间:2023-10-16

我正在创建一个应用程序,该应用程序从用户输入生成年,月,周和天我已经尝试过了,但只有几年和几个月的工作例如,当我输入 30 天时,它说 1 个月、2 周和 2 天,而不仅仅是 1 个月谢谢

// Description: This program prompts the user for an integer,    which will represents the total
////number of days; The program then will break it apart into years, months, weeks, and days ////(each one of these will have their own local variables), and once this is done, the outcome will be     //displayed on the screen.
//Enter no.of days : 1234Years : 3Months : 4Weeks : 2Days : 5
#include <iostream>
#include <cmath>
using namespace std;
const int daysInWeek = 7;
const int days_in_month = 30;
const int days_in_year = 365;
const int days_in_days = 1;
int main()
{
 //Local variables
 int totalDays;
 int years;
 int months;
 int weeks;
 int days;
 //program info/intro
 cout << "My name is Dianan";
 cout << "Program 1: Convert Number of Days to Years, Months,     Weeks, and Days" << endl;
 cout << "----------------------------------------------------------------    ----- n";
 //get numbers and develop math progress
 cout << "Enter the total number of days : ";
 cin >> totalDays;
 years = totalDays / days_in_year;
 months = (totalDays % days_in_year) / days_in_month;
 weeks = (days_in_month % daysInWeek);
 /*weeks = (totalDays%days_in_year) / daysInWeek;*/
 days = (totalDays% days_in_year) % daysInWeek;
 // Display it in the screen
 cout << "          " <<  
 cout << "Years = " << years << 
 cout << "Months = " << months << endl;
 cout << "Weeks = " << weeks << endl;
 cout << "Days = " << days << endl;
 system("pause");
 return 0;
}

正如已经建议的那样,更好的方法是跟踪剩余的日子:

years = totalDays / days_in_year;
totalDays %= days_in_year;
months = totalDays / days_in_month;
totalDays %= days_in_month;
weeks = totalDays / days_in_week;
totalDays %= days_in_week;
days = totalDays;