Go Down

### Topic: Problem with simple multiplication (Read 4472 times)previous topic - next topic

#### garrett

##### Nov 12, 2006, 05:00 pm
I'm trying to use an A/D pin, read the value, simply multiply by 1000, and display the result back at the computer.  I'm using long for the big integer I'm making, but to no avail.

Here is the code:

Code: [Select]
`int inputPin = 0;               // Analog Input pin #int inputValue = 0;long result;void setup(){  Serial.begin(9600);           // open serial port, set to 9600 baud. }void loop(){  delay(1000);                          // waits for a second    inputValue = analogRead(inputPin);    //Read input value  result = inputValue*1000;             // Convert to bigger number  Serial.print("inputValue is: ");      //Display input value  Serial.println(inputValue,DEC);      Serial.print("result is: ");          //Display result of multiplication  Serial.println(result,DEC);    Serial.println();}`

Here is the output (just a sample of it):

Code: [Select]
`inputValue is: 137result is: 5928`

As you can see, if the inputValue is 137, the result is obviously wrong.

Any ideas at what I'm doing wrong?  BTW: I'm using the ATMega168, and Arduino 0006 to write the software.

Thanks,

Garrett

#### mellis

#1
##### Nov 12, 2006, 06:47 pm
It might be that because the two numbers you're multiplying are both int's, the result is calculated as an int before being stored in result.  You might try appending an "L" to the end of the 1000:

Code: [Select]
`  result = inputValue*1000L;`

#### garrett

#2
##### Nov 12, 2006, 07:00 pm
Ah, fixed it myself.. The line that says:

Code: [Select]
`result = inputValue*1000;`

Should be:

Code: [Select]
`result = inputValue*1000L;`

Since both 'inputValue' and '1000' were considered 'int' type variables, the program lopped off some bits before assigning it to 'result'.

Fix: Force '1000' to be a long type of number by using '1000L'.

Sorry, I'm a noob to C.  Hope this helps others too.

- - Garrett

#### garrett

#3
##### Nov 12, 2006, 07:02 pm
Looks like you beat me to the post button Mellis, thanks though

Go Up

Please enter a valid email to subscribe