C++ primer练习第一章

这篇博客包含了多个C++编程练习,涉及变量声明、循环控制以及错误修复。练习中指出了代码片段的错误,如未声明变量、预期表达式错误等,并提供了修正后的代码示例,包括计算整数之和的循环、倒序输出数字以及打印指定范围内数字的程序。
摘要由CSDN通过智能技术生成

练习1.6:解释下面程序片段是否合法

#include<iostream>
using namespace std;
int main()
{
        cout<<"The sum of"<<v1;
            <<"and"<<v2;
            <<"is"<<v1+v2<<std::endl;
}

报错如下:

exam_1_6.cc: In function ‘int main()’:
exam_1_6.cc:5:22: error: ‘v1’ was not declared in this scope
    5 |  cout<<"The sum of"<<v1;
      |                      ^~
exam_1_6.cc:6:6: error: expected primary-expression before ‘<<’ token
    6 |      <<"and"<<v2;
      |      ^~
exam_1_6.cc:6:15: error: ‘v2’ was not declared in this scope
    6 |      <<"and"<<v2;
      |               ^~
exam_1_6.cc:7:6: error: expected primary-expression before ‘<<’ token
    7 |      <<"is"<<v1+v2<<std::endl;
      |      ^~

答:不合法(1)未声明变量v1,v2(2)error: expected primary-expression
error: expected primary-expression的解决

1.4控制流

练习1.4.1

编写程序,使用while循环将50到100的整数相加

#include<iostream>

int main()
{
	int i=50;
	int sum=0;
	while(i<=100)
	{
		sum+=i;
		i++;
	}
	std::cout<<sum;
}

练习1.10

#include<iostream>

int main()
{
	int i=10;
	while(i>=0)
	{
		std::cout<<i<<std::endl;
		i--;
	}
	return 0;
}

练习1.11

#include<iostream>
using namespace std;
int main()
{
	int i,j;
	cout<<"Please enter two numbers to indicate a range:"<<endl;
	cin>>i>>j;
	while(j>=i)
	{
		cout<<j<<endl;
		j--;
	}
	return 0;
}

练习1.13

#include<iostream>
using namespace std;
int main()
{
	int sum;
	for(int i=50;i<=100;i++)
	{	
		sum+=i;
	}
	cout<<sum;
}
#include<iostream>
using namespace std;
int main()
{
	for(int i=10;i>=0;i--)
	{	
		cout<<i<<endl;
	}
}
#include<iostream>
using namespace std;
int main()
{
	int i,j;
	cout<<"Please enter two numbers to indicate a range:";
	cin>>i>>j;
	for(;j>=i;j--)
	{
		cout<<j<<endl;
	}
}

练习1.15

[Error] cannot declare '::main' to be a global variable #main的参数列表漏掉看作一个全局变量
[Error] found ':' in nested-name-specifier, expected '::'#将endl后面使用了冒号而非分号
[Error] 'endl' is not a class, namespace, or enumeration#推测冒号常用于类,命名空间,枚举
[Error] 'Updata' was not declared in this scope#字符串字面常量的两侧漏掉了引号将updata视作一个变量
[Error] expected '}' before 'master'
[Error] 'cout' does not name a type#漏掉了第二个输出运算符
[Error] expected unqualified-id before 'return'#漏掉了return语句的分号
[Error] expected declaration before '}' token
[Error] invalid conversion from 'const char*' to 'int' [-fpermissive]#无法将一个字符串字面值传递给int
[Error] 'v' was not declared in this scope; did you mean 'v2'?#使用了"v"而非"v1"

练习1.16

#include<iostream>
using namespace std;
int main()
{
	int value=0,sum=0;
	while(cin>>value)
	{
		sum+= value;
	}
	cout<<sum;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值