关于求和的问题,如何解决?(语言-c++)

为啥最后运行结果C会等于1呢,求解答


#include <iostream>
using namespace std;
int main()
{
    int a,b,c;
    c=a+b;
    cout<<"a+b="<<c<<endl;
    return 0;

a和b没赋值,所以a和b的值为内存位置的随机值,可能是0,1,或者其他值,所以其和也是随机值,比如1,或者其他值;

给a和b赋个初始值即可。

测试如下:


 
#include <iostream>
using namespace std;
int main()
{
    int a=1,b=2,c;
    c=a+b;
    cout<<"a+b="<<c<<endl;
    return 0;
    
}

img

  • 帮你找了个相似的问题, 你可以看下: https://ask.csdn.net/questions/7647183
  • 这篇博客也不错, 你可以看下C++面试笔试必知必会-栈实现队列队列实现栈
  • 除此之外, 这篇博客: 【疑问】C++结构体(数组)指针作为函数参数,会不会修改实参的值?中的 实例 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • #include<iostream>
    using namespace std;
    
    //英雄结构体
    struct hero
    {
    	string name;
    	int age;
    	string sex;
    };
    
    void changeArray(hero arr[])
    {
    	arr[0].name = "猪猪侠";
    }
    
    //打印数组
    void printHeros(hero arr[], int len)
    {
    	for (int i = 0; i < len; i++)
    	{
    		cout << "姓名: " << arr[i].name << " 性别: " << arr[i].sex << " 年龄: " << arr[i].age << endl;
    	}
    }
    
    int main() {
    
    	struct hero arr[5] =
    	{
    		{"刘备",23,"男"},
    		{"关羽",22,"男"},
    		{"张飞",20,"男"},
    		{"赵云",21,"男"},
    		{"貂蝉",19,"女"},
    	};
    	
    	 //获取数组元素个数
    	int len = sizeof(arr) / sizeof(hero);
    
    	printHeros(arr, len); 
    	
    	changeArray(arr);
    	
    	cout << "=============" << endl;
    	
    	printHeros(arr, len);
    	
    	system("pause");
    
    	return 0;
    }
    
    姓名: 刘备 性别: 男 年龄: 23
    姓名: 关羽 性别: 男 年龄: 22
    姓名: 张飞 性别: 男 年龄: 20
    姓名: 赵云 性别: 男 年龄: 21
    姓名: 貂蝉 性别: 女 年龄: 19
    =============
    姓名: 猪猪侠 性别: 男 年龄: 23
    姓名: 关羽 性别: 男 年龄: 22
    姓名: 张飞 性别: 男 年龄: 20
    姓名: 赵云 性别: 男 年龄: 21
    姓名: 貂蝉 性别: 女 年龄: 19
    
  • 您还可以看一下 朱有鹏老师的朱老师C++第1部分-1.1.为什么会有C++这门语言课程中的 1.1.1.朱老师C++课程整体介绍小节, 巩固相关知识点