开发者

i am not getting why is the answer coming it as 5,i'll write the program below

#include开发者_Go百科<stdio.h>
void main()
{
 int cats,dogs,others,total_pets;
 cats=10;
 dogs=43;
 others=36;
 total_pets=cats+dogs;
 printf("there are %c  total pets are",total_pets);
}


Use %d in place of %c in the printf.

The value of total_pet is 53. When you use %c in printf you are trying to print the character whose ASCII value if 53 which happens to be 5.


See here for ASCII table : http://web.cs.mun.ca/~michael/c/ascii-table.html

And why it printing 5 :-

Actually its '5' not 5. Your code is printing character 5 not decimal 5. When you use %c to print value of an integer variable, printf convert integer value with character equivalent (as you have seen in ASCII table).

You can try this code (or you should write your own)

void main()
{
    int num;
    printf("Printing ASCII values Table...\n\n");
    num = 1;
    while(num<=255)
    {
       // here you can see how %c and %d works for same variable
       printf("\nValue:%d = ASCII Character:%c", num, num); 
       num++;
     }
    printf("\n\nEND\n");
}

Happy coding.


Why are you formatting it as %c Use %d

printf("there are %d total pets are",total_pets);


why are you using %c. use %d

%c single character
%d and %i both used for integer type
%u used for representing unsigned integer
%o octal integer unsigned
%x,%X used for representing hex unsigned integer
%e, %E, %f, %g, %G floating type
%s strings that is sequence of characters


Because 53 is the place in the ascii chart where '5' sits.

Use %d in your printf instead.


%c is the character specifier so printf("there are %c total pets are",total_pets); prints the ascii character with the value 53, which is the 5 character.


%c is to print a character. Try changing it to %d for the integer value.

What you are printing is the integer value interpreted as a character.


You need to change the %c to a %d.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜