【问题标题】:Why I am getting wrong output 2686924 instead of 281?为什么我得到错误的输出 2686924 而不是 281?
【发布时间】:2018-01-21 12:09:29
【问题描述】:

我是 C++ 新手,正在学习它。

这是我为问题 4 编写的代码,但它没有给出输出。

我有两个问题:

  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;
    }
    

它显示错误“cout”未在范围内声明,但我仅使用 c++。

  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;
    printf("Answer is:");
    printf("%d",answer);
    }
    

这给出输出 2686924。输出错误应该打印 281。我检查了每一行但没有显示错误请说明为什么没有显示输出。

【问题讨论】:

  • 你认为answer=answer; 会做什么?
  • 7+8+14; 也不做任何事情,也不做它下面的任何行。我猜你打算写a += a2
  • 以及你必须使用 std::cout
  • answer 打印所有数字的总和
  • 知道了,但只需使用 using namespace std;或 std::cout 'cout' 未在范围内声明,但我仅使用 c++。

标签: c++ sum output cout


【解决方案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;

另外,你明白这行文字吗?你不能没有空格对!代码也是如此。

【讨论】:

  • 你明白这行文字哈哈哈幽默吗??
  • @HariomSingh 不,只是我讨厌运算符周围没有空格。我将它的“unreadability”与英语中的等价物进行比较。
  • 感谢您的回答,但仍然显示错误 cout is not declared in the scope.
  • @anthony 你需要std:: 命名空间,因为cout 肯定不会在std 命名空间之外声明。不要做using namespace std;,只要做std::cout &lt;&lt; whatever &lt;&lt; std::endl;
  • 谢谢它的工作。但是你能告诉我 std::cout 和 cout 有什么区别吗?
猜你喜欢
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2019-01-25
  • 2023-02-21
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多