1

I'm making an IF-statement where I want something to happen if the inserted number ends with a zero. The following doesn't work:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int year;

    printf("Skriv in ditt födelseår\n");
    scanf("%d", &year); printf("Du är %d", 2013 - year); printf(" år gammal");

    if ( 2013 - year.endsWith('0') ) {
        printf("Grattis, du fyller jämnt iår!\n");
    }



    return 0;

}

So, if the result of 2003 - year (year is typed in by the user) ends with a zero, I want to print something. How do I make it work?

2 Answers2

9

See whether the result can be divided by 10 without a remainder:

if ( ( 2013 - year ) % 10 == 0 ) {
    printf("Grattis, du fyller jämnt iår!\n");
}
devnull
  • 118,548
  • 33
  • 236
  • 227
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • @user3004300 yes, please accept this answer by clicking the respective button to honour Frerich Raave's effort to answer your question. – PhillipD Nov 18 '13 at 11:49
0

You are reading year from console input and you want to something if the input ends with 0, than you shouldn't test (2013-year). Assume you enter 2013 (which does does not end with 0)

if ( 2013 - year.endsWith('0') ) {
        printf("Grattis, du fyller jämnt iår!\n");
    }

will print the message you have in there. Because you are testing for the difference between years.

I think you need to rewrite the condition as

if (year.endsWith('0') ) {
           printf("Grattis, du fyller jämnt iår!\n");
    }

OR

if ( year  % 10 == 0 ) {
    printf("Grattis, du fyller jämnt iår!\n");
}

Whichever you prefer. I don't see the point of subtracting year from 2013.

Pandrei
  • 4,843
  • 3
  • 27
  • 44