-2
#include <stdio.h>

int folgenglied(int);

int main(){
    int n, m;
    printf("Type a number in\n");
    scanf("%d", &n);
    m = folgenglied(n);
    printf("%d ist the Folgenglied", m);
}

int folgenglied(int n) {
    int x;
    x = 1 / (n + 2);
    return x;
}

I want to write the result of the folgenglied in the second printf call, but it always prints out 0. I don’t understand what’s wrong with my code.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
kilston
  • 25
  • 5
  • 2
    Why are you trying to pass `int` to `folgenlied`? And note that you will only ever get 0, -1, 1, or an error since `x` is an `int`. – General Grievance Dec 22 '22 at 21:36
  • Your input is `n`, so unless there's something I'm missing, that's it. It probably "didn't work" because you're trying to store the result of a fraction into an `int` variable. – General Grievance Dec 22 '22 at 21:41
  • I fail to see how "_What has got to come to the print function after the colon,?_" could be an on-topic question for Stack Overflow. The question still lacks many details and lacks basic research effort IMHO. – wovano Dec 22 '22 at 21:53
  • 1
    @wovano True. The title was not updated, but should be. The body is now a duplicate of integer division yaddayadda. – Yunnosch Dec 22 '22 at 21:54

1 Answers1

2
  1. I would start from the proper formating.
  2. Function return value. You can use this value.
  3. Always check the result of the scanf function
  4. Integer division will return 0, -1, or 1 (abstracting from the division by zero)
#include <stdio.h>

double folgenglied(int);

int main(void)
{
    int n,m;
    double result;
    printf("Type a number in\n");
    if(scanf("%d", &n) == 1)
    {
        result = folgenglied(n);
        printf("%f ist the Folgenglied", result);
    }
}

double folgenglied(int n )
{
    double x = 0.0;
    if(x != -2) x=1.0/(n + 2);
    return x;
}
0___________
  • 60,014
  • 4
  • 34
  • 74