- python是动态的,C++是静态的
Python和C ++有着根本的区别。一个主要区别是C ++是静态类型的,而Python是动态类型的。
vehicle_doors = 4
vehicle_speed = 3.0
vehicle_acceleration = 1.5
vehicle_on = True
vehicle_gear = 'D'
vehicle_dors = vehicle_doors + 1
ython自动计算出vehicle_doors是一个整数,vehicle_speed是一个浮点数,vehicle_on是一个布尔变量。变量赋值是动态的。在Python中,不需要指定将进入变量的值的类型
在C ++中,上述代码都不起作用。在定义值之前,需要声明变量类型; 因此,C ++是一种静态类型语言。下面是代码的C ++版本:
int vehicle_doors;
float vehicle_speed;
float vehicle_acceleration;
char vehicle_gear;
bool vehicle_on;
vehicle_doors = 4;
vehicle_speed = 3.0;
vehicle_acceleration = 1.5;
vehicle_gear = 'D';
vehicle_on = True;
vehicle_doors = vehicle_doors + 1;
- Python基于查看回车符和新换行符来检测代码行的结尾。C ++使用分号来实现相同的目的。
- Python使用缩进将代码语句组合在一起,但C ++使用花括号。
-
Python是动态类型的,而C ++是静态类型的。就像你如何声明变量一样,你需要声明你的函数。
因为C ++是静态类型的,所以需要指定函数输入变量的数据类型以及函数返回的数据类型。
···
// Leave the main function as is
include<iostream>
float distance(float velocity, float acceleration, float time);
int main() {
// TODO: The following are examples you can use to test your code.
// You will need to uncomment them to get them working.
std::cout << distance(3, 4, 5) << std::endl;
std::cout << distance(7.0, 2.1, 5.4) << std::endl;
return 0;
}
//TODO: define your function
float distance(float velocity, float acceleration, float time){
float distance_;
distance_ = velocity * time + 0.5 * acceleration*time*time;
return distance_;
}
···
定义一个新的类型
typedef vector < vector <float> > t_grid;
函数重载
bool close_enough(float v1, float v2) {
if (abs(v2-v1) > 0.0001 ) {
return false;
}
return true;
}
bool close_enough(vector < vector <float> > g1, vector < vector <float> > g2) {
int i, j;
float v1, v2;
for (i=0; i<g1.size(); i++) {
for (j=0; j<g1[0].size(); j++) {
v1 = g1[i][j];
v2 = g2[i][j];
if (abs(v2-v1) > 0.0001 ) {
return false;
}
}
}
return true;
}
bool test_normalize() {
//declare several variables on one line
vector < vector <float> > unnormalized, normalized, result;
unnormalized = zeros(2, 2);
normalized = zeros(2,2);
int i,j;
for (i=0; i<2; i++) {
for(j=0; j<2; j++) {
unnormalized[i][j] = 1.0;
normalized[i][j] = 0.25;
}
}
result = normalize(unnormalized);
bool correct;
correct = close_enough(normalized, result);
if (correct) {
cout << "! - normalize function worked correctly!\n";
}
else {
cout << "X - normalize function did not work correctly.\n";
cout << "For the following input:\n\n";
show_grid(unnormalized);
cout << "\nYour code returned the following:\n\n";
show_grid(result);
cout << "\nWhen it should have returned the following:\n";
show_grid(normalized);
}
return correct;
}
while
for loop
switch
#include <iostream>
int main() {
char gear_status = 'N';
switch(gear_status) {
case 'D' :
std::cout << "Driving Forward" << std::endl;
case 'N' :
std::cout << "Not Moving - Neutral" << std::endl;
case 'P' :
std::cout << "Not Moving - Parked" << std::endl;
case 'R':
std::cout << "Driving in Reverse" << std::endl;
}
std::cout << "Your car is currently in gear: " << gear_status << std::endl;
return 0;
}
网友评论