calebmcarr
calebmcarr

Reputation: 19

Program gives me gigantic number when adding small numbers

I've already searched, but could not quite find my answer. I'm relatively new to C (in high school), and a problem ALWAYS pops up in any math program I ever write. I'll have some small numbers and when they are run through, the result is some gigantic number. I have copied programs off of sites and books, and the same issue occurs. Here's the source code for one example:

#include <stdio.h>

int main(){
    int c, k = c + 273;
    printf("Enter your celsius degree here...\n");
    scanf("%d",&c);
    printf("%d",&k);
}

It's a simple code, but still comes out weird.

Upvotes: 0

Views: 73

Answers (3)

Sid
Sid

Reputation: 21

Try this:

int c = 0, k = 0;
k = c +273;
scanf("%d", &c);
printf("%d", k);

The initialization of k and c will help remove the garbage values stored in them and you will get the correct output.

Upvotes: 0

unxnut
unxnut

Reputation: 8839

You never assigned a value to c before using it to compute k. So, what you wnat for your code is probably:

#include<stdio.h>
    int main(){
    int c, k;
    printf("Enter your celsius degree here...\n");
    scanf("%d",&c);
    k = c + 273;
    printf("%d",k);
}

Notice that when you print, you do not use &. That would be giving the address of k.

Upvotes: 1

Jules Gagnon-Marchand
Jules Gagnon-Marchand

Reputation: 3781

In your code, c is not being initialized. In c, non initialized variables have undefined behavior (garbage) values.

Upvotes: 0

Related Questions