C语言代写

#include <iostream>
using namespace std;

 

int main (void) {

cout << “Hello world!”;

return 0;

}

 

Some explanations

To get input and print output in C++, use the cin and cout functions.  cin is used for input and cout for standard output (to the display).  But first you need the appropriate library.

Include statements

Your program must start with include statements to import the necessary libraries.  The only library you will need for this program is the iostream library which contains the cin and cout functions.  In addition you will need to open the standard namespace to access these functions.  That is the function of these lines above the main function.

#include <iostream>
using namespace std;

Using cin and cout

To get input from the keyboard into a variable named x:

int x = 0;
cin >> x;

To send output to the display:

cout << x;

Note that this will not print the value of x on a new line, but you can use endl to specify a newline.  Below I’m printing the value of x on a new line (with some explanatory text) and then printing another line:

cout << endl << “The value of x is: ” << x << endl;

Return values

By convention, main functions return the value 0 if everything went well. Other values can be used to denote various forms of failure or output results.

Modifying the program

Modify hello.cpp to have the following behaviour:

  • Obtain a number as input using cin.
  • If the number is an even integer, print “Even” (no quotes).
  • If the number is an odd integer, print “Odd” (no quotes).
  • If the number is neither an odd integer nor an even integer, print “Nonint” (no quotes). This must be the only output from your program (e.g. no other prompts). There must be no newline (endl) at the end of these either.
  • uname@hostname: ~$ ./hello_world
  • 5
  • Odd
  • uname@hostname: ~$ ./hello_world
  • 42
  • Even
  • uname@hostname: ~$ ./hello_world
  • 5
  • Nonint

Testing

This program was quite simple, but we will illustrate how we might test this program. Download the zip file in this folder, save it, and unzip it in your lab1 directory:

uname@hostname: ~$ unzip assgmt1test.zip

uname@hostname: ~$ ls

1.gt          2.in          3.in          a.out         hello_world   test.py

1.in          2.gt          3.gt          hello.cpp     assgmt1test.zip

Run the program test.py it contains:

uname@hostname: ~$ ./test.py

If you have correctly modified hello.cpp as specified above, you will see:

Running test 1…

passed

Running test 2…

passed
Running test 3…
passed

Passed 3 of 3 tests

test.py is a Python script, as you might have guessed. The “shebang” (#!) line tells linux to use python to run it. It uses input/output “redirection” (>,<) to pass input (*.in) to your hello_world program and compare (diff) this output (*.out) against specified output (*.gt).