-2

I am new to programming and learning C from schildt's teach yourself C. I am trying to make a function that returns square. but when I input numbers with decimals it outputs as whole number. why does it do that? my program :

    #include <stdio.h>
int get_sqr(void);

void main()
{
    float x;
    x = get_sqr();
    printf("square : %f",x);
    return 0;
}

int get_sqr(void)
{
    float y;
    printf("enter a number : ");
    scanf("%f",&y);
    return y*y; /*returning the square result to assignment argument */
}
absinth
  • 27
  • 2
  • 6
    Because `int get_sqr(void);` – StoryTeller - Unslander Monica Sep 19 '17 at 10:06
  • can you please explain? – absinth Sep 19 '17 at 10:07
  • _This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting [the shortest program necessary to reproduce the problem](https://stackoverflow.com/help/mcve) before posting._ – Sourav Ghosh Sep 19 '17 at 10:07
  • 2
    You said that the get_sqr function that take void parameter must return a int change `int get_sqr(void);` to `float get_sqr(void);` – m.nachury Sep 19 '17 at 10:07
  • 1
    @absinth your functions return an `int`, but it should return a `float`. In other words: `int get_sqr(void)` -> `float get_sqr(void)` – Jabberwocky Sep 19 '17 at 10:07
  • 2
    You do understand what the `int` means in `int get_sqr(void);`, right? – babon Sep 19 '17 at 10:09
  • thank you m.nachury. such a foolish mistake got my head spinning this whole time :) – absinth Sep 19 '17 at 10:10
  • 4
    I get it now, return operator returns same type with which the function is declared.thank you all. or am I wrong ? – absinth Sep 19 '17 at 10:12
  • @absinth Yes, See my answer. You've declared a function returning `int` so even though the `return` statement is a `float` it gets truncated to an `int` to conform to the function prototype which is `int get_sqr(void)`. – Persixty Sep 19 '17 at 10:15
  • 1
    PS: Schlidt's Teach Yourself C is a terrible terrible book. I'm not sure what the best modern books are but Herbert Schlidt is responsible for propagating some very nasty habits. Find an alternative. Look here https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – Persixty Sep 19 '17 at 10:45

1 Answers1

2

It's because the return value of get_sqr() is int. Although the value in the return statement is a float C implicitly converts that to an int because the function is declared returning an int:

int get_sqr(void)

Change that line to

float get_sqr(void)

and the full float value of y*y will be returned.

Persixty
  • 8,165
  • 2
  • 13
  • 35