Zynastor
Zynastor

Reputation: 91

Add Variable If in for

I want to display the variable hm more than 0, but it always displays 0. How can I fix this?

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    long long result = 1;
    int n;
    int i;
    char str[13500];
    int hm=0;  
    scanf("%d", &n);    
    for(i=0;i<n;i++) {
        result *= 9;
        sprintf(str, "%lld", result);
        printf("%c ",str[0]);
        if (str[0] == 9) {
            hm=hm+1;
        }      
    }
    printf("%d", hm); 
    return 0;
}

Upvotes: 0

Views: 82

Answers (2)

tue2017
tue2017

Reputation: 51

This is because when you use 'sprintf' it will store the content as a string in the buffer str.

Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str. The size of the buffer should be large enough to contain the entire resulting string (see snprintf for a safer version). A terminating null character is automatically appended after the content. After the format parameter, the function expects at least as many additional arguments as needed for format.

Link: http://www.cplusplus.com/reference/cstdio/sprintf/

So, just change your 'if' statement to

if (str[0] == '9')

treat the value 9 as a character by enclosing it between single quotes. Hopefully, this should work for you.

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

str[0] == 9 looks wrong. Typically, character codes of number characters are not equal to the numbers they represent. For example, the character code for 9 is 57 (0x39) in ASCII.

To obtain character code from fixed character (character literal), surround the character with ''. The condition should be str[0] == '9'.

Upvotes: 2

Related Questions