Home > Enterprise >  Basic C language task about printing a certain number using %.3f
Basic C language task about printing a certain number using %.3f

Time:01-19

i just started studying programming at school, and i am so lost already. Here's the task:

Answer all 3 tasks in a separate file and return it. What is the result if the format string (control character) of the printf function is %.3f and the number to be printed is 456.87654321 0.17023 443.14159

How do i even do this? My code is this but it's obviously wrong.

#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Give a number 1\n");
scanf("%i", &num1);

printf("Answer is on %.3f", &num1);

return 0;

}

It gave me 0 as answers or 0.000 what ever. Only 0's.

I don't know what to do really, my teacher is already on another subject and has no time helping me much.

CodePudding user response:

This source code:

#include <stdio.h>


int main(void)
{
    printf("%.3f\n", 456.87654321);
    printf("%.3f\n", 0.17023);
    printf("%.3f\n", 443.14159);
}

produces this output:

456.877
0.170
443.142

CodePudding user response:

You declared num1 to be an int (integer... whole numbers only).

Then you read that number from the keyboard.
I'm guessing you're entering 456.87654321.
(hint, that is not a whole number. it will not fit in an int)

Then you try to print it out with:

printf("Answer is on %.3f", &num1);

This has several problems.

  • %.3f is for printing out doubles, not ints.
  • You passed the "address" (& sign) of the number you wanted to print.
    Just pass the variable directly

Fixing up your code, I get:

#include <stdio.h>

int main() {
    double num1;                       // Declare DOUBLE, not INT

    printf("Give a number 1\n");
    scanf("%f", &num1);                // Get a DOUBLE from input, not an INT

    printf("Answer is on %.3f", num1); // Remove the & (address)

    return 0;
}
  •  Tags:  
  • c
  • Related