go away spammer

### Author Topic: Simple number conversion/ math problem?  (Read 1553 times)

0 Members and 1 Guest are viewing this topic.

• Supreme Robot
• Posts: 611
##### Simple number conversion/ math problem?
« on: April 10, 2010, 10:27:07 PM »
I can't seem to find out why this isn't working.  I'm trying to implement something into a program of mine, and using variables does not work.  If I put the value of the variable in, it'll work.  Well, here's the code.

What I tried to use was an array to take place of the values in my code, however it just didn't work.  I guessed that it had something to do with double and int, so I tried to make the first array "a" a double, and the second array "b" was int, then covert the double to the int, but that still didn't work.

This WORKS:

Code: [Select]
` for(ct=1;ct<2000;ct++) { if (ct<=255) { if (ct == 1) DDRD|=(1<<PORTD0); //LED1 On OCR1A++; //LED1 brightness up } else if ((ct>255) && (ct<=510)) { if (ct == 510) DDRD&=~0x01; //LED1 Off OCR1A--; //LED1 brightness down }        }`
This does NOT work:

Code: [Select]
` unsigned int ct=1,i,a[17],max,interval; double num; max = 1360; num = 16/3; interval = max/num; for(i=0;i<17;i++) { a[i]=(i/3)*interval; } for(ct=1;ct<2000;ct++) { if (ct<=a[3]) { if (ct == a[0]+1) DDRD|=(1<<PORTD0); //LED1 On OCR1A++; //LED1 brightness up } else if ((ct>a[3]) && (ct<=a[6])) { if (ct == a[6]) DDRD&=~0x01; //LED1 Off OCR1A--; //LED1 brightness down } }`

I even tried this:
Code: [Select]
` unsigned int ct=1,i,b[17]; double num,max,interval,a[17]; max = 1360; num = 16/3; interval = max/num; for(i=0;i<17;i++) { a[i]=(i/3)*interval; b[i]=(int)a[i]; } for(ct=1;ct<2000;ct++) { if (ct<=b[3]) { if (ct == b[0]+1) DDRD|=(1<<PORTD0); //LED1 On OCR1A++; //LED1 brightness up } else if ((ct>b[3]) && (ct<=b[6])) { if (ct == b[6]) DDRD&=~0x01; //LED1 Off OCR1A--; //LED1 brightness down } }`What's going on?
« Last Edit: April 10, 2010, 10:38:22 PM by corrado33 »

#### tim_wang

• Jr. Member
• Posts: 32
##### Re: Simple number conversion/ math problem?
« Reply #1 on: April 11, 2010, 05:47:37 PM »
The problem with your code is that you are dividing unsigned ints which returns unsigned int.

unsigned int ct=1,i,a[17],max,interval;
double num;
max = 1360;
num = 16/3; // num = 5, not 5.33!
interval = max/num; // 1360 / 5 = 272, not 255!
for(i=0;i<17;i++)
{
a=(i/3)*interval; // a = [0 0 0 272 272 272 544 544 544 816 816 816 1088 1088 1088 1360 1360 1360]
}