I'm experiencing the following problem printing unsigned numbers . Here's whats happening: When I input a negative value in the array and then try to print it, I can't print the number but other amount is printed.
int cant;
int a[30][30];
int printequation (){
int x,y;
for (x=0;x<cant;x++){
for (y=0;y<cant+1;y++){
if(y==cant){
printf(" = %d",a[x][y]);
}else{
if (y==0)
printf(" %dX%d",a[x][y],(y+1));
else{
if(a[x][y]>0){
printf(" + ");
}else{
printf(" - ");
}
printf("%uX%d",a[x][y],(y+1)); /*<-----------------here*/
}
}
}
printf("\n");
}
return 0;
}
Here's an example:
input: -2 -2 -2
output: -2x1 -4294967294x2 = -2 /*here It should print -2 but can't get it*/
Avoid mixing mis-matched printf()
format specifiers with argument types. @ouah
//v
int a[30][30];
...
printf("%uX%d",a[x][y],(y+1));
// ^
To print a signed int
without its "sign" and work with the entire range of INT_MIN ... INT_MAX
, a number of approaches:
Give up on INT_MIN
and use abs()
@Keith Thompson
printf("%d", abs(x)); // fails for 2's complement INT_MIN
Convert to wider integer. Fails when wider integer not available - rare.
printf("%lld", llabs((long long) x));
Convert to corresponding unsigned
. Maybe trouble on rare machines whose unsigned
positive range is the same as int
positive range.
unsigned u = (unsigned) i;
if (i < 0) u = UINT_MAX - u;
printf("%u", u);
Print digits seprately
int msdigits = i/10;
int lsdigit = i%10;
if (msdigits) {
printf("%d", abs(msdigits));
}
printf("%d", abs(lsdigit));