Re: long veriable causes problem
From: B. v Ingen Schenau (bart_at_ingen.ddns.info)
Date: 04/30/04
- Next message: Francis Glassborow: "Re: [C++] Vectors & Dynamic allocation"
- Previous message: B. v Ingen Schenau: "Re: Header file + implementation file with template"
- In reply to: Ronen Kfir: "long veriable causes problem"
- Next in thread: Francis Glassborow: "Re: long veriable causes problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 30 Apr 2004 11:38:38 +0200
Ronen Kfir wrote:
> Hi,
> The following code works only with int veriable defenitions. with long
> I get wrong results, -1 does not terminate program & negative numbers
> give back odd numbers.
>
> please help.
>
>
> TIA
> Ronen
>
>
> //calculates an admin digit based on //
> //program rules.//
>
> #include<stdio.h>
>
> //veriable definition//
> long result(long x);
> long bikoret;
> long number;
>
> void main()
According to the definition of C and C++, main must return an int, so
int main()
> {
> puts ("\nPlease enter a positive integer");
> scanf ("%d",&number); //first number input//
This is where your error lies.
When scanf processes the %d specifier, it expects to store the result in an
object of type 'int'. You pass it an object of type 'long int' and because
of this mismatch you get the dreaded undefined behaviour.
The correct way to read a value into a long int is
scanf ("%ld", &number);
>
> while (number!=-1 //exit from loop if number=-1//
> {
> if (number>=0) //if number>0 comete //
> //the following code//
> {
> bikoret=result(number); //send veriavle //
> //number as an argoment //
> //to result() function. //
> //Then asign the return value of result() to
> //
> //bikoret veriable//
> printf ("Administration digit is %d\n", bikoret); //print output of
Here you should also use %ld to get correct results.
> bikoret//
> }
> else
> {
> puts ("\npositive integres only!"); //if number<0//
> //don't calculate admin digit//
> }
> scanf ("%d",&number); //next number input//
Same here.
Bart v Ingen Schenau
-- a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
- Next message: Francis Glassborow: "Re: [C++] Vectors & Dynamic allocation"
- Previous message: B. v Ingen Schenau: "Re: Header file + implementation file with template"
- In reply to: Ronen Kfir: "long veriable causes problem"
- Next in thread: Francis Glassborow: "Re: long veriable causes problem"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|