0

write about the greatest common divisor using c language. How can I put a "please entre positive number" statement when I typing a negative or float number in this code?

# include <stdio.h>

int GCD (int a, int b) {

    while ( b != 0 ) { 
              if ( a > b ) {
             a = a – b ;
          } else {
            b = b – a ;
         } return a;
          }

    int main (void) {
        int a, b,  result ;

        printf(“Type two positive integers”);
        scanf( %d %d, &a, &b);

        result = GCD ( a, b) ;
        printf(“GCD (%d, %d) = %d \n” , a , b, result );

        return 0;

    }
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Welcome to SO! It looks like this was edited or copy-pasted from a rich text editor like a word document. Can you format it in plain text? – ggorlen Nov 24 '19 at 00:42
  • 1
    in `GCD` you know how to test if `a` is greater than `b`, but dont know how to test if a number is less than zero? – yano Nov 24 '19 at 00:47
  • 1
    Please revise the question title. It has nothing to do with GCD. It's about validation. Consider doing a search on input validation, and using fgets/sscanf instead of simple scanf, if you HAVE to implement validation. – dash-o Nov 24 '19 at 06:59

1 Answers1

2

How can I put a "please entre positive number" statement when I typing a negative or float number in this code?

You can check the values of a and b and repeated the scanf when either of them are not positive values:

while( ( 2 != scanf( "%d %d", &a, &b) ) || (a < 0 || b < 0) )
{
    printf("Error: please enter two positive numbers\n");
    continue;
}
artm
  • 17,291
  • 6
  • 38
  • 54
  • 1
    This will not work because `scanf` accepts negative numbers for the `%u` format. Per C 2018 7.21.6.2 12, `u` “Matches an optionally signed decimal integer,…” The code `#include ` / `int main(void) { unsigned x; printf("Return value of scanning a negative number with %%u is %d.\n", sscanf("-3", "%u", &x)); }` shows the return value is 1. – Eric Postpischil Nov 24 '19 at 00:57
  • 1
    maybe just a simple check on the values themselves would do – artm Nov 24 '19 at 01:07
  • @chux-ReinstateMonica that makes sense, thanks – artm Nov 24 '19 at 06:16