Problem with simple multiplication

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:

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.print("result is: ");          //Display result of multiplication

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

inputValue is: 137
result 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.



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:

  result = inputValue*1000L;

Ah, fixed it myself… The line that says:

result = inputValue*1000;

Should be:

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

Looks like you beat me to the post button Mellis, thanks though :)