0
int main(){

    int  N, i, j=0;

    float MA, MB, asum=0, bsum=0, y;

    printf("\number of pairs: "); scanf("%d", &N);

    int a[N+1], b[N+1], c[N+1];


    for(i=1; i<N+1; i++){

        printf("\na%d",i); printf("=");
        scanf("%f", &a[i]);


        printf("b%d",i); printf("=");
        scanf("%f", &b[i]);

        printf("\n aSUM= %.6f \n",asum);
        asum+=a[i];
        printf("\n aSUM= %.6f \n",asum);

    } 

The idea of this code is simple. User inputs int or float values, then they get summed and outputted as a float value. However I'am getting astronomical values straight away. Fe. if it tries to make addition of 0 and 7, it outputs a value of 1088421888.000000. What the heck is going on?? :D

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
SmOg3R
  • 149
  • 12
  • 1
    Remember, if this is `C` and not `C++` your definition of `main()` must be `int main(void)` or `int main(int argc, char* argv[])`. see http://stackoverflow.com/questions/2108192/what-are-the-valid-signatures-for-cs-main-function for details –  Dec 14 '13 at 18:56
  • On which operating system, with which compiler, and with which compiler options, are you compiling all this...? – Basile Starynkevitch Dec 14 '13 at 19:36

3 Answers3

5

You should enable all warnings with a modern C compiler (like GCC 4.8).

 int a[N+1], b[N+1], c[N+1];
 //...later
     scanf("%f", &a[i]);

This cannot work: %f is for scanf(3) a control format requiring a float pointer, and &a[i] is a pointer to an int. (and GCC would have warned about that).

And you have other errors too. Please enable all warnings -e.g. compile with gcc -Wall

BTW, it is much better to put \n at the end of your printf format control string (not at the beginning!).

Basile Starynkevitch
  • 216,767
  • 17
  • 275
  • 509
2

You are using wrong specifier for int. It will invoke undefined behavior. You will get anything. You are lucky that you are not getting the desired result!

haccks
  • 100,941
  • 24
  • 163
  • 252
2

sscanf doesn't know about the type of their pointer parameters, so you read in floats in integer pointers. Thus, integer pointers were as float interpreted.

You need to scanf into a temporary float variable, and then convert this to integers. So:

float  theFloat;
sscanf("%f", &theFloat);
N[a]=theFloat;
peterh
  • 1
  • 15
  • 76
  • 99
  • O so now if I input 5.6 it gets converted to 5, therefore 0+5.6 becomes 5... I might as well just use ints and get the same result.. I need to input and output values with commas. – SmOg3R Dec 14 '13 at 19:04
  • No! You have right! You need to handle the main array as a float array! Your current code rounds the floats during the integer conversion. – peterh Dec 14 '13 at 19:06
  • 1
    Thanks! I don't get it why people tend to answer in such a complex way lol. "change {int a[N+1]} to {float a[n+1]}" is all that needed. Thanks again – SmOg3R Dec 14 '13 at 19:15