Home > database >  C programming return 0
C programming return 0

Time:12-10

I wrote the code to calculate the sum up to a certain number n, if it is not a natural number to write that it is not, or if a number is not entered to say that it was not entered and the program stops working, all that is done, but it simply does not load this part below the if loop, how do I fix that and put returns or some other option?


int main() {
  int i, n, s = 0;
  printf("input n: ");
  scanf("%d", &n);
 if (n<0) {
    printf(" Not natural number");return 0;}
 if (n != scanf("%d", &n)) {
    printf("No number!");return 0;}
  for (i = 1; i <= n; i  )
    s = s   i * i;
  printf("s is: %d", s);
  return 0;
}

CodePudding user response:

You need to check the return value from scanf to see if the scan was successful. It returns the number of scanned values. Also, error messages should be printed to the standard error stream. Try this:

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

int main(void)
{
    int c, i, n, s;

    printf("input n: ");    
    c = scanf("%d", &n);
    if (c != 1) {
        fprintf(stderr, "No number!\n");
        exit(EXIT_FAILURE);
    } else if (n < 0) {
        fprintf(stderr, "Not natural number\n");
        exit(EXIT_FAILURE);
    }
    s = 0;
    for (i = 1; i <= n; i  ) {
        s = s   i * i;
    }
    printf("s is: %d\n", s);
    return 0;
}

CodePudding user response:

Your program logic is wrong:

 if (n<0) {
    printf(" Not natural number");return 0;}
 // here you call scanf  again without any reason
 // just remove the two lines below
 if (n != scanf("%d", &n)) {
    printf("No number!");return 0;}

You want this:

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

int main() {
  int i, n, s = 0;
  printf("input n: ");
  scanf("%d", &n);
  if (n < 0) {
    printf(" Not natural number"); return 0;
  }

  for (i = 1; i <= n; i  )
    s = s   i * i;
  printf("s is: %d", s);
  return 0;
}

Don't try to validate input with scanf. It can't be done. Don't care about input validation until you are more proficient in C.

  • Related