I have this working code that assigns fixed values to some unsigned char variables:
#include <stdio.h>
#include <stdlib.h>
int main2()
{
unsigned char a,b;
a=1,b=2;
a=(a+b)/2;
printf("\nAverage: %d\n%18d",a,sizeof(a));
return 0;
}
But when I try reading in the values instead, like so:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned char a,b;
scanf(" %d", &a); scanf(" %d", &b);
a=a,
b=b,
a=(a+b)/2;
printf("\nAverage: %d\n%18d",a,sizeof(a));
return 0;
}
it doesn't work. Why not? It seems that scanf takes only the last value when I print the sum.
This is my best attempt to fix the code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned char b;
unsigned short int a;
scanf(" %u", &a);
scanf(" %u", &b);
b=b;{
b=(a+b);
unsigned short int a;
scanf(" %u", &a);{
b=(a+b)/3;
printf("\nAverage: %u",b);
printf("\n sizeof: %d",sizeof(b));
}
}
return 0;
}
General advice: take warnings to heart when compiling. Copying and pasting your code gave me the following:
So taking all warning into account, I can re-order your first program to this (which works!):
If you really do want to use unsigned chars, go with %hhu: