编程基础/变量示例 C++
外观
< 编程基础
以下示例演示了 C++ 中的数据类型、算术运算和输入。
// This program demonstrates variables, literal constants, and data types.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int i;
double d;
string s;
bool b;
i = 1234567890;
d = 1.23456789012345;
s = "string";
b = true;
cout << "Integer i = " << i << endl;
cout << "Double d = " << d << endl;
cout << "String s = " << s << endl;
cout << "Boolean b = " << b << endl;
return 0;
}
Integer i = 1234567890 Real r = 1.23457 String s = string Boolean b = 1
每个代码元素代表
//
开始注释#include <iostream>
包含标准输入输出流//
#include <sstream>
包含标准字符串流//
using namespace std
允许引用string
、cout
和endl
,而无需编写std::string
、std::cout
和std::endl
。int main()
开始主函数,该函数返回一个整数值{
开始代码块int i
定义名为 i 的整型变量;
结束每行 C++ 代码double d
定义名为 d 的双精度浮点型变量string s
定义名为 s 的字符串变量bool b
定义名为 b 的布尔变量i = , d = , s =, b =
将字面量值分配给相应的变量cout
是标准输出<<
将下一个元素定向到标准输出endl
结束当前行return 0
从 main 返回值 0,表示主函数成功完成}
结束代码块
// This program demonstrates arithmetic operations.
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a;
int b;
a = 3;
b = 2;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << a + b << endl;
cout << "a - b = " << a - b << endl;
cout << "a * b = " << a * b << endl;
cout << "a / b = " << a / b << endl;
cout << "a % b = " << a + b << endl;
return 0;
}
a = 3 b = 2 a + b = 5 a - b = 1 a * b = 6 a / b = 1 a % b = 5
每个新的代码元素代表
+, -, *, /, and %
分别代表加法、减法、乘法、除法和模运算。
// This program converts an input Fahrenheit temperature to Celsius.
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://wikibooks.cn/wiki/C%2B%2B_Programming
#include <iostream>
using namespace std;
int main() {
double fahrenheit;
double celsius;
cout << "Enter Fahrenheit temperature:" << endl;
cin >> fahrenheit;
celsius = (fahrenheit - 32) * 5 / 9;
cout << fahrenheit << "° Fahrenheit is " << celsius << "° Celsius" << endl;
return 0;
}
Enter Fahrenheit temperature: 100 100° Fahrenheit is 37.7778° Celsius
每个新的代码元素代表
cin >> fahrenheit
从标准输入读取下一个整数并将该值分配给 fahrenheit 变量