Why I am getting wrong output 2686924 instead of 281?

时间:2017-08-13 14:06:19

标签: c++ sum output cout

I am new to C++ and learning about it.

Here is a code I have written for Problem No 4 but it's not giving the output.

I am having two problems:

  1. #include<iostream>
    #include<stdio.h>
    
    int main(){
    int a,b,c,d,e,f;
    int a2,b2,c2,d2,e2,f2;
    
    int answer;
    
    a=1;
    b=2;
    c=3;
    d=4;
    e=5;
    f=6;
    
    a2=11;
    b2=22;
    c2=33;
    d2=44;
    e2=55;
    f2=66;
    
    7+8+14;
    a+a2;
    b+b2;
    c+c2;
    d+d2;
    e+e2;
    f+f2;
    
    answer=answer;
    cout<<"Answer is"<<answer;
    }
    

It showed me error 'cout' is not declared in the scope but i am using c++ only.

  1. But when i changed this code:

    #include<iostream>
    #include<stdio.h>
    
    int main(){
    int a,b,c,d,e,f;
    int a2,b2,c2,d2,e2,f2;
    
    int answer;
    
    a=1;
    b=2;
    c=3;
    d=4;
    e=5;
    f=6;
    
    a2=11;
    b2=22;
    c2=33;
    d2=44;
    e2=55;
    f2=66;
    
    7+8+14;
    a+a2;
    b+b2;
    c+c2;
    d+d2;
    e+e2;
    f+f2;
    
    answer=answer;
    printf("Answer is:");
    printf("%d",answer);
    }
    

This give output 2686924. The output is wrong it should print 281. I have checked every line but no error shows please tell why output is not showing.

1 个答案:

答案 0 :(得分:1)

您的代码中有许多语句实际上没有任何内容,

7+8+14;
a+a2;
b+b2;
c+c2;
d+d2;
e+e2;
f+f2;

answer=answer;

你知道,答案是未初始化的。你永远不会在代码中设置它的值,所以你需要像

这样的东西
// Initialize `answer' here
answer = 7 + 8 + 14;
answer = answer + a + a2;
answer = answer + b + b2;
answer = answer + c + c2;
answer = answer + d + d2;
answer = answer + e + e2;
answer = answer + f + f2;

另外,doyouunderstandthislineoftext?你不能没有空间吧!那么代码也是如此。