你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

C++练习题(六)

2021-11-18 7:54:59
  1. Write a C++ program that displays the address of a float variable. Display the address first in hexadecimal and then in decimal.

Solution to Q1:

#include <iostream>
using namespace std;
float f;
float *fp;
int main() {
 f = 3.1415;
 fp = &f;
 cout << "The hexadecimal address of f is " << fp << endl;
 cout << "The decimal address of f is " << (int) fp << endl;
}
  1. Write a C++ program that has the two following variables (and no other variables):
      int val;
      int *ptr;
    The program must enter a value, add 3 to the value and display the result. Link the pointer to the
    integer variable but do not use the variable val anywhere else in the program.

Solution to Q2:

#include <iostream>
using namespace std;
int val;
int *ptr;
int main() {
 ptr = &val;
 cout << "Enter an integer value ";
 cin >> *ptr;
 *ptr = *ptr + 3;
 cout << "The result is " << *ptr << endl;
}
  1. Write a C++ program that checks the value of an integer pointer. If the value is NULL, display an appropriate message. Hint: set the pointer to NULL before checking it.

Solution to Q3:

#include <iostream>
using namespace std;
int *p;
int main() {
 p = NULL;
 if (p == NULL) {
 cout << "This is a NULL pointer\n";
 }
}
  1. Study the following fragment of a C++ program:
    float* val1, val2;
      a) is val1 a pointer?
      b) is val2 a pointer?

Solution to Q4(b):

val2 is not a pointer because the star “belongs” to val1. Thus val2 is a float variable and not a pointer.
  1. Write a C++ function that is a void function with three float parameters. The first parameter is a value in NZ dollars, the second parameter is the value after converting the NZ dollars to Samoan
    tala, and the third parameter is the value after converting the NZ dollars to the Papua New Guinea kina. The purpose of the function is to convert the value in NZ dollars to Samoan tala and Papua
    New Guinea kina. Write a suitable main program to test your function.

Solution to Q5:

#include <iostream>
using namespace std;
void convert(float NZD, float & WST, float & PGK);
int main() {
 float value, tala, kina;
 cout << "Enter an amount in NZ dollars: $";
 cin >> value;
 convert(value, tala, kina);
 cout << "NZ $" << value << " = " << tala;
 cout << " Samoan tala\n";
 cout << "NZ $" << value << " = " << kina;
 cout << " Papua New Guinea kina\n";
}
void convert(float NZD, float & WST, float & PGK) {
// check the latest exchange rates...
 WST = NZD / 0.5593;
 PGK = NZD / 0.4086;
}