1

I'm new to c and im trying to learn how to use the scanf function to pass in data and then the printf function to show me the printed results.

This seems like it should be eas,y but my expected outputs do not match what gets returned. My IDE is vscode

#include <stdio.h>

#define pi 3.14159

int main()
{
    float size;
    float radius;
    scanf("this is the value : %f",&radius);
    size = (2/3)*pi*(radius*radius*radius);
    printf("%f",size);
    return 0;
}

here you can see what i inpute and what gets printed

After that I went to make an easier program to understand the concept and I'm getting a similar but different issue. instead of returning 0 every time now it prints the same constant

#include <stdio.h>

int main() 
{ 
    int a; 
    scanf("This is the value %d", &a); 
    printf("Input value read : a = %d", a); 
    return 0; 
}

Here you can see the output i get for the second program

Any ideas for whats going wrong and how i could fix it?

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
  • 3
    Do you realise that `(2/3)` is `0`? Integer division. I suggest `(2 * pi / 3)` – Weather Vane Aug 29 '20 at 20:11
  • thank you all for the help. i tried to cast the int division as a float but apparently i dont now how to that so i took the (2 * pi / 3) and that worked for me. Also knowing that you need to have your input matching the scanf command when you try to assign a value would've been a cool thing to be taught. anyways thanks again all for the help code works now. – MedicinalShrimp Aug 29 '20 at 20:24

1 Answers1

0

You seem to expect scanf to print a message and then to acquire a value:

scanf("this is the value : %f",&radius);

No. This obtained just by printing the message and then aquiring the value with scanf:

printf("Please insert the value :\n");
if (scanf ("%f",&radius) == 1)
{
    /* ... */
}

Please note the check on scanf return value, that is the number of variables succesfully aquired. In this case we expect it to be 1, as the only format specifier is %f.

That message before %f made scanf actually expect exactly that string (whitespaces included) before the float number. Inserting just the input number (5, in your example) made scanf discard the input as it wasn't matching the given string, and no value was stored, so that radius remained uninitialized and the execution resulted in undefined behavior. Additionally, that leading 2/3 is calculated with integer arithmetics and the result is 0; use 2.0/3.0 to force the use of float arithmetics.


The issue with the test involving %d is quite similar; you just see the random uninitialized value of a that is not written by scanf for the reasons explained above.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39