C++练习
开始C++学习
// myfirst.cpp--displays a message
#include <iostream> // a PREPROCESSOR directive
int main() // function header
{ // start of function body
using namespace std; // make definitions visible
cout << "Come up and C++ me some time."; // message
cout << endl; // start a new line
cout << "You won't regret it!" << endl; // more output
// If the output window closes before you can read it,
// add the following code:
// cout << "Press any key to continue." <<endl;
// cin.get();
return 0; // terminate main()
} // end of function body
兔子个数
// carrots.cpp -- food processing program
// uses and displays a variable
#include <iostream>
int main()
{
using namespace std;
int carrots; // declare an integer variable
carrots = 25; // assign a value to the variable
cout << "I have ";
cout << carrots; // display the value of the variable
cout << " carrots.";
cout << endl;
carrots = carrots - 1; // modify the variable
cout << "Crunch, crunch. Now I have "
<< carrots << " carrots." << endl;
// cin.get();
return 0;
}
输入输出
// getinfo.cpp -- input and output
#include <iostream>
int main()
{
using namespace std;
int carrots;
cout << "How many carrots do you have?" << endl;
cin >> carrots; // C++ input
cout << "Here are two more. ";
carrots = carrots + 2;
// the next line concatenates output
cout << "Now you have " << carrots << " carrots." << endl;
// cin.get();
// cin.get();
return 0;
}
数学函数
// sqrt.cpp -- using the sqrt() function
#include <iostream>
#include <cmath> // or math.h
int main()
{
using namespace std;
double area;
cout << "Enter the floor area, in square feet, of your home: ";
cin >> area;
// cin.get();
double side;
side = sqrt(area);
cout << "That's the equivalent of a square " << side
<< " feet to the side." << endl;
cout << "How fascinating!" << endl;
// cin.get();
return 0;
}
没有返回值函数
// ourfunc.cpp -- defining your own function
#include <iostream>
void simon(int); // function prototype for simon()
int main()
{
using namespace std;
simon(3); // call the simon() function
cout << "Pick an integer: ";
int count;
cin >> count;
simon(count); // call it again
cout << "Done!" << endl;
// cin.get();
// cin.get();
return 0;
}
void simon(int n) // define the simon() function
{
using namespace std;
cout << "Simon says touch your toes " << n << " times." << endl;
} // void functions don't need return statements
有返回值函数
// convert.cpp -- converts stone to pounds
#include <iostream>
int stonetolb(int); // function prototype
int main()
{
using namespace std;
int stone;
cout << "Enter the weight in stone: ";
cin >> stone;
int pounds = stonetolb(stone);
cout << stone << " stone = ";
cout << pounds << " pounds." << endl;
// cin.get();
// cin.get();
return 0;
}
int stonetolb(int sts)
{
return 14 * sts;
}