Same math and numbers different answers? - c++

im writing a simple program that you give a number of days and it gives back the number of years weeks and days that equal to the numbers of days you give.
but i noticed that you can get two different answers even tho when i checked the math it makes sense in both cases .
can someone please please explain to me why the answers are different and which one is correct
#include<iostream>
using namespace std;
int main()
{
int y;
int d,w;
int Days;
cin>>d;
y=d/365;
int LessThanAYearDays = d%365;
Days=LessThanAYearDays%7;
w=LessThanAYearDays/7;
int SameDays = d%7;
cout<<"answer1 is : "<<y<<" "<<w<<" "<<Days<< "\n";
cout<<"answer2 is : "<<y<<" "<<w<<" "<<SameDays<< "\n";
return 0;
}

There are not an exact multiple of weeks in a year, so you are displaying different things. They will be the same in years divisible by 7.
E.g. Assume that a given year starts on a Tuesday.
Days corresponds to how many days past the last Tuesday you are.
SameDays corresponds to what day you are on.
See also the distinction that std makes between a std::chrono::duration, which is a count of time, and a std::chrono::time_point, which is a count of time since a particular date.

Related

Is there a way for C++ to detect that when a value ends with a certain number it'll do an if-statement? [duplicate]

This question already has answers here:
How does the modulus operator work?
(5 answers)
Closed 2 years ago.
it's my first time posting in here! I know that my question doesn't sound really correct, but I'm really new to programming. In my program, I need that if a user enters a number (1 <= 365) then the program will tell which day is it. Then I came up with a solution but I don't know if C++ can even do it. For example, if A/7= 3.6 and B/7= 2.1 or C/7=2.9 then it'll read the last decimal and do a different if function every time (for example if it ends with .6 program then says it's Thursday and .9 it's Sunday and so on and so on). I hope it kind of makes sense.
Thanks
#include <cstdio>
main()
{
float n, D;
printf("Enter the number of the day n:\n");
scanf("%f", &n);
D = n/7
if (D = )/*here I'm trying that if D ends with some number it'll do this*/
{
printf("It's Monday")
}
}
How about multiply 10 then '%' to get the remainder?

Getting the day info only from a date int C/C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a program that is getting a date from some protocol, in format of DD/MM/YYYY.
The Problem is that I need to know the info of that day(day of the week, day in the year...) and I don't know how to do it.
Usually, when I want to get a day info, I am using time(time_t*) and convert the result to tm struct using localltime_r(tm*, time_t*) and then I have everything i need.
But in this case, this is not the current time(so I can not use time(time_t*)) and I don't have nothing except the date.
I can create a new tm struct and fill only tm_year, tm_mon, tm_mday and use mktime(tm*), but I am not sure if this will give me the right detail's of the desired date.
You might consider using Howard Hinnant's free, open-source date/time library. It works with C++11 and later, ported to gcc, clang and VS. It has been accepted into the C++20 draft specification.
Example code:
#include "date/date.h"
#include <iostream>
#include <sstream>
int
main()
{
using namespace std;
using namespace date;
istringstream in{"09/07/2018"};
sys_days sd;
in >> parse("%d/%m/%Y", sd);
cout << "Day of the week is " << weekday{sd} << '\n';
cout << "Day of the year is " << sd - sys_days{year_month_day{sd}.year()/1/0} << '\n';
}
Output:
Day of the week is Mon
Day of the year is 190d
If you would rather do the computations yourself, here are extremely efficient non-iterative public domain algorithms for calendrical computations. The library referenced above is nothing but a type-safe wrapper around these algorithms with more pleasant syntax.
In case you wanted to get write methods which get the day of week/year as opposed to using a library, here's what I would do.
You're going to need to take leap years into account. For any given year, determine whether or not it is a leap year. Something like this would work (using a formula found here: https://en.wikipedia.org/wiki/Leap_year#Algorithm:
bool isLeapYear(short year)
{
bool leapYear = false;
if (((year % 4 == 0 && year % 100 != 0)) || (year % 400 == 0))
leapYear = true;
return leapYear;
}
From this, calculating the day of the year is straightforward. Simply add up all the days for each month, if it is a leap year, add 29 days onto your tally for day of year if you come across February.
As for finding the day of the week, it really helps if you start with some lower bound for the year (in this case LOWYEAR = 1760) and start with the first day of that year (STARTDAYOFWEEK = 2). Each day of the week is corresponds to a number (0-6) where Sunday is 0, Monday is 1, etc.
int DayOfWeek(void)
{
//jan 1 1760 was tuesday (2)
short dayCount = STARTDAYOFWEEK;
for (unsigned i = LOWYEAR; i < year; i++)
{
if (isLeapYear(i))
dayCount += 2;
else
dayCount++;
}
return (dayCount + dayOfYear) - 1) % DAYSINWEEK;
}
Finding the day of week is now really easy, after calculating dayCount, the day of week is found by adding dayCount with dayOfYear and modding by DAYSINWEEK (6).
The resulting number will correspond to the day of week (0-6).

Printing a value changes the output of the code

Few hours ago, a competition was held on CodeForces , this was one the questions of the competition -
Problem C (You dont have to read/solve it to answer the question)
EDIT : Adding the question here as requested, again, one does not necessarily have to read it.
Slastyona and her loyal dog Pushok are playing a meaningless game that
is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in
each round, a natural number k is chosen. Then, the one who says (or
barks) it faster than the other wins the round. After that, the
winner's score is multiplied by k2, and the loser's score is
multiplied by k. In the beginning of the game, both Slastyona and
Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all
n games was recorded. She managed to recall the final results for each
games, though, but all of her memories of them are vague. Help
Slastyona verify their correctness, or, to put it another way, for
each given pair of scores determine whether it was possible for a game
to finish with such result or not.
Input In the first string, the number of games n (1 ≤ n ≤ 350000) is
given.
Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 10^9) –
the results of Slastyona and Pushok, correspondingly.
Output For each pair of scores, answer "Yes" if it's possible for a
game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
So I solved it, and after the competition was over, me and my friends were discussing the problems when they asked me what was my answer coming for the following test case -
1
1 1
I said it was "Yes" on my IDE (Dev-C++ 5.11), (as it was supposed to be)
But when we ran it on ideone, it came out to be "No" !!
I thought there must be a problem with my code only, so i tried debugging it when i came across this problem,
My Code -
#include<stdio.h>
using namespace std;
long long int iscube(long long int n)
{
long long int lo = 0;
long long int hi = 1000000;
while(lo < hi)
{
long long int mid = (lo+hi)/2;
if(mid*mid*mid < n)
lo = mid+1;
else
hi = mid;
}
return lo;
}
int main()
{
long long int a,b;
int n;
scanf("%d",&n);
while(n--)
{
scanf("%I64d %I64d",&a,&b);
long long int c = a*b;
long long int cb = iscube(c);
//printf("%lld",cb)
if(cb*cb*cb == c)
{
if(a%cb == 0 && b%cb == 0)
printf("Yes\n");
else
printf("No\n");
continue;
}
printf("No\n");
}
}
When i give the input as
1
1 1
in the above code, the answer comes out to be "No"
BUT if I ONLY uncomment the line above the if statement in the while loop in the main() function,
the answer would be "1 Yes"
(these outputs are the outputs i got when i ran the code on ideone, when running on Dev-C++ 5.11 , i got "Yes" and "1 Yes" as expected)
Now while i was thinking that my my answer of codeforces would be evaluated as WA, After the system test, it came out to be Accepted!
Does anyone have any idea on why this issue is arising?
(Also, could someone add the appropriate tags, if any)
Turn up your warnings, you have undefined behavior in your scanf:
warning: length modifier 'I64' results in undefined behavior or no effect with 'd' conversion specifier [-Wformat]
scanf("%I64d %I64d",&a,&b);
If you change it to scanf("%lld %lld",&a,&b); (C++11), then you'll have defined behavior, however since you're using C++, just use a stream instead:
std::cin >> a >> b;
Demo

a lot of decimal value storage in C++

I wanted to write a program that returns how many months we could survive when we're given
our monthly expenditure, amount of disposable income, and interest rate (all in integers).
For instance, if we start with disposable income = 1000, interest rate = 5%, monthly expenditure = 100, then
after first month: 1000*1.05 - 100 = 950, we have 950 dollars left
after second month: = 950*1.05 - 100 = 897.5
and so on, and in the end, we can survive 14 months.
I wrote the following code in C++:
int main(){
int i=0;
int initialValue;
int interest;
int monthly;
double value=1.0*initialValue;
double r=1+1.0*interest/100;
while(value > 0){
if(value < monthly){
break;
}
else
{
value=value*r-monthly;
i++;
}
};
cout<<i;
return 0;
}
but for sufficiently large values of initialValue and small values of monthly, the program I wrote runs very slowly to the degree that it's unusable. Is there a problem with the code that makes it run not well (or very slow)?
Any help would be greatly appreciated.
double cannot store numbers precisely. One consequence of this is when you subtract a very small number from a very large number, the result is not changed from the original large value.
One solution to this problem is to use an int to do your calculations. Think of the values as the number of pennies, rather than the number of dollars.
A few notes:
The *1.0's are pointless. Instead, take advantage of implicit and explicit casts:
double value=initialValue;
double r=1+(double)interest/100;
++i is faster than i++.
value=value* can be rewritten as value*=.
You can mix the first two conditionals. Remove the if...break and change the while loop to while (value > 0 && value < monthly).
On the face of it, the reason this runs slowly is the large number of iterations. However, you didn't specify any specific numbers and I would expect this code to be able to execute at least a million iterations per second on any reasonably fast processor. Did you really expect to need to calculate more than 1 million months?
Apart from the novice style of the code, the underlying problem is the algorithm. There are very simple formulae for making these calculations, which you can find here: https://en.wikipedia.org/wiki/Compound_interest. Your situation is akin to paying off a loan, where running out of money equals loan paid off.

C++ reverse number with digit adding

Hi to all thank all in advance to those who tried to answer or answer and part of this question.
Calculate the sum of the digits of the year.
Calculate the absolute value of the difference between the year and the ’reverse’ of the year.
Calculate the number of even factors of the day.
Calculate the greatest common divisor of the day, month and year.
Calculate the number of steps required to solve the Collatz problem for
the month
These are my tasks that I need to fulfill, as Engineering student this how far I went in this. In the following codes I expect something like this
19
90
0
1
0
T M B B
The answer that I get is
Please enter your birthdate (dd mm yyyy): 12 11 1981
19
8468304
Press any key to continue . . .
8468304
How to get it right I know that my equation is right or(formula, method). However this is what I know.
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
cout << "Please enter your birthdate (dd mm yyyy): ";
int day, month, year, count,rev;
int sum = 0;
cin >> day>> month >>year;
while (year!=0)
{
int count = year%10;
sum +=count;
year /= 10;
}
while(year>0)
{
rev = year%10;
year=year/10;
}
cout<<sum<<endl;
cout << rev;
system ("pause");
return 0;
}//end main
Please help!
After your first loop, while (year != 0), you don't reset the value of year, so it remains at zero and the second loop doesn't execute at all.
You need to save the value of year and use it when you start the second loop.
Just a note on organisation: I'd suggest to write a subroutine/function for every task, like
int digit_sum(int year) {
/* ... */
return sum;
}
int reverse_difference(int year) {
/* ... */
return diff;
}
and so on. This way you'll also prevent errors like modifying the year variable during the first calculation without saving the original value (which you did, as David Winant already pointed out).