0

// 2 つの町の間の距離は 380 km です。二つの町から一台の乗用車と大型トラックが同時に出発した。車の速度が大型トラックの速度よりも 5 km\ 速く、2 台の車が 4 時間後に出会ったことがわかっている場合、2 台の車を運転した速度は? 必要な情報を計算して表示するには、動的メモリ割り当てとポインターを使用します。

// The distance between two towns is 380km. A car and a lorry started from the two towns at the same time. At what speed drove the two vehicles, if the speed of the car is with 5km\ faster than the speed of the lorry and we know that they met after 4 hours? Use Dynamic Memory Allocation and Pointer in calculating and Displaying the needed info.

#include <iostream.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

int main ()
{
    int t=4;
    int d=380;
    int dt=20;
    int dd;
    int * ptr;
    int * ptr2;
    ptr  = (int*) malloc (500*sizeof(int));
    ptr2 = (int*) malloc (500*sizeof(int));
    dd=d-dt;
    ptr = dd/8;
    ptr2 = ptr+5;
    cout << " The Speed of the Car is: " << ptr << endl;
    cout << " The Speed of the Lorry is: " << ptr2 << endl;
    return(0);
}

どうすればこれを実行できますか? すべての変数で動的メモリ割り当てを使用する方法は? ありがとう。

4

2 に答える 2

1

ポインタがptr指す値を取得するには、演算子を使用して逆参照する必要があります*ptr

したがって、

ptr = dd/8
ptr2 = ptr+5;

*ptr = dd/8
*ptr2 = *ptr+5;

この:

cout << " The Speed of the Car is: " << ptr << endl;
cout << " The Speed of the Lorry is: " << ptr2 << endl;

cout << " The Speed of the Car is: " << *ptr << endl;
cout << " The Speed of the Lorry is: " << *ptr2 << endl

;

于 2013-08-30T07:39:12.587 に答える