Home > Mobile >  Trying to read a positive value in c
Trying to read a positive value in c

Time:10-09

i just want to make sure that i read a positive value for x not sure whats wrong here

#include <stdio.h>

void main() {
    unsigned x;
    int i;
    do {
        printf("donner un nombre\n");
        scanf("%u", &x);
    } while (x <= 1);
    /*
    for (i = 0; i  ; i < x) {
        int prime = 0;
        int x = 2;
        do {
            if (i % x == 0 ) {
                prime = 1;
            }
            x  ;
        } while (prime == 0 && x < i);
        
        if (prime == 0) {
            printf("%i",i);
        }
    }
    */
}

CodePudding user response:

If you are using Linux as a development environment, you can take a look at man 3 scanf. This will give you the function's documentation.

That being said, the function returns a number which indicates how many valid inputs were read.

Knowing that, you can read a positive integer with the following code to check for read status:

int rc;
unsigned int x;

rc = scanf("%u", &x);
if (rc == 1) {
    // valid input data
}

CodePudding user response:

Unsigned is bad choice

First at all you change unsigned type to integer int, that alloved you to scan negative numbers such as -1, -5,...

Wrong condition in loop

Also there is bug in do while loop, where you scan until the x <= 1 but number 1 is positive number, so you have to change it to x < 1

Final code will looks like this:

#include <stdio.h>

int main() {
    int x;
    do {
        printf("donner un nombre\n");
        scanf("%u", &x);
    } while (x < 1);

    // your code working with positive x

    return 0;
}
  •  Tags:  
  • c
  • Related