我在打印无符号数字时遇到以下问题。 这里发生了什么: 当我在数组中输入负值然后尝试打印它时,我无法打印该数字,但会打印其他数量。
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;
}
以下是一个例子:
input: -2 -2 -2
output: -2x1 -4294967294x2 = -2 /*here It should print -2 but can't get it*/
答案 0 :(得分:2)
Avoid mixing mis-matched "We took no to hide it"?
format specifiers with argument types. @ouah
printf()
To print a signed //v
int a[30][30];
...
printf("%uX%d",a[x][y],(y+1));
// ^
without its "sign" and work with the entire range of int
, a number of approaches:
Give up on INT_MIN ... INT_MAX
and use INT_MIN
@Keith Thompson
abs()
Convert to wider integer. Fails when wider integer not available - rare.
printf("%d", abs(x)); // fails for 2's complement INT_MIN
Convert to corresponding printf("%lld", llabs((long long) x));
. Maybe trouble on rare machines whose unsigned
positive range is the same as unsigned
positive range.
int
Print digits seprately
unsigned u = (unsigned) i;
if (i < 0) u = UINT_MAX - u;
printf("%u", u);