In the following code why does it not multiply correctly?
I should have a result of 39600 but instead I get -25936.
Weird or what?
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println((3600*11));
delay(2000);
}
In the following code why does it not multiply correctly?
I should have a result of 39600 but instead I get -25936.
Weird or what?
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println((3600*11));
delay(2000);
}
I should have a result of 39600 but instead I get -25936.
Why would you expect to fit 39600 in an int?
Serial.println((3600UL*11UL));
will print 39600.
Hmmm, I guess I don't know all the rules yet.
So because the arduino has some computing limitations I assume I will not be able to do the following:
int monthDays[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
void setup() {
Serial.begin(9600);
Serial.println("setup");
}
void loop() {
Serial.println("START LOOP");
unsigned long years = 2012;
unsigned long months = 1;
unsigned long days = 27;
unsigned long hours = 11;
unsigned long mins = 27;
unsigned long secs = 30;
unsigned long monthsInDays = 0;
unsigned long monthsInSecs;
unsigned long i;
unsigned long leapYearsInSec = ((years-1972)/4)*31622400UL;
unsigned long yearsInSec = ((years - 1970)-((years-1972)/4))*31536000UL;
Serial.println("VAR");
if (((years-1972)%4)==0){
if (months > 2){
monthsInDays = 1;
for (i=0;i<=(months-2);i++){
monthsInDays = (monthsInDays + monthDays[i]);
}
}else{
monthsInDays = 0;
for (i=0;i<=(months-2);i++){
monthsInDays = (monthsInDays + monthDays[i]);
}
}
monthsInSecs = monthsInDays*86400UL;
}else{
monthsInDays = 0;
for (i=0;i<=(months-2);i++){
monthsInDays = (monthsInDays + monthDays[i]);
}
monthsInSecs = monthsInDays*86400UL;
}
Serial.println("AFTER IF");
unsigned long daysInSecs = (days*86400UL);
Serial.println(hours);
unsigned long hoursInSecs = (hours*3600UL);
unsigned long minsInSecs = (mins*60UL);
unsigned long unix = (secs+minsInSecs+hoursInSecs+daysInSecs+monthsInSecs+yearsInSec+leapYearsInSec);
Serial.println("START");
Serial.println(secs);
Serial.println(minsInSecs);
Serial.println(hoursInSecs);
Serial.println(daysInSecs);
Serial.println(monthsInSecs);
Serial.println(yearsInSec);
Serial.println(leapYearsInSec);
Serial.print("UNIX IS: ");
Serial.println(unix);
Serial.println();
}
Sparked:
I will not be able to do the following:
The code you wrote here is using unsigned long, which does have the range needed to do this. I do not believe you'll have any problem.
Your first example was using unadorned integers, which have a range of only -32768...32767. This is not sufficient to evaluate the calculations correctly.
With this number in a multiplication 31622400UL, you are however getting close to the Unsigned long limit, 4294967295UL
Thirty one and a half million is a good long way from four billion, where years since 1972 are involved.