Home > OS >  After running code, the output is always zero
After running code, the output is always zero

Time:10-23

I don't understand what makes the output zero.

I wanted to put 1000 as x and 100.00 as y, and I want the output to be 8000.00 not 00.

#include<stdio.h>

int main()
{
    int x,i;
    double y, result= x;
    scanf("%d %lf",&x,&y);

    for(i=0; i<3; i  )
    {
        y/=100;
        result = result (result*y);
    }

    printf("%.2lf\n",result);
    return 0;   
}

CodePudding user response:

You just declare the variable x, but not initialize it. So it causes undefined behavior.

int x,i; // <-- you declare the variable, but you didn't assign a value to x

Then, you assign result to x:

double y, result= x; // so now result is undefined behavior

Only now you give x a value by: scanf("%d %lf",&x,&y); but it's too late. result is now undefined behavior.

You should change your code to this:

#include<stdio.h>

int main()
{
    int x,i;
    double y;
    scanf("%d %lf",&x,&y); // <-- now you give x a value
    result= x; // <-- so now result is not undefined behavior anymore.


    for(i=0; i<3; i  )
    {
        y/=100;
        result = result (result*y);
    }

    printf("%.2lf\n",result);
    return 0;   
}

CodePudding user response:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char * *argv, char * *envp) {
    int x = 0, i = 0;
    double y = 0.0, result = 0.0;
    scanf ("%d %lf", &x, &y);
    result = (double) (x);
    for (i = 0; i < 3;   i) {
        y = y / 100.0;
        result = result   (result * y);
    }
    printf ("%.2lf\n", result);
    return (EXIT_SUCCESS);
}
  •  Tags:  
  • c
  • Related