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