저는 프로그래밍이 처음이고 배열, 포인터 및 함수에 여전히 문제가 있습니다. 이 문제가 무엇이고 어떻게 고칠 수 있는지 알고 싶습니다. 특히 포인터가 함수에서 작동하지 않는 이유입니다. 다음은 내가 작성하려는 프로그램입니다. 사용자가 정의한 수의 테스트 점수를 저장할 수있을만큼 큰 배열에 대한 포인터를 동적으로 생성하는 프로그램을 작성합니다. 모든 점수가 입력되면 (주 함수에서) 평균 점수에 대해 DOUBLE을 반환하는 함수로 배열을 전달해야합니다. 사용자 출력에서 평균 점수는 소수점 이하 두 자리로 형식화되어야합니다. 포인터 표기법을 사용하십시오. 배열 표기법을 사용하지 마십시오.
#include <iostream>
#include <iomanip>
#include <memory>
using namespace std;
double getAverage(int, int);
int main()
{
int size = 0;
cout << "How many scores will you enter? ";
cin >> size;
unique_ptr<int[]> ptr(new int[size]);
cout << endl;
int count = 0;
//gets the test scores
for (count = 0; count < size; count++)
{
cout << "Enter the score for test " << (count + 1) << ": ";
cin >> ptr[count];
cout << endl;
}
//display test scores
cout << "The scores you entered are:";
for (count = 0; count < size; count++)
cout << " " << ptr[count];
cout << endl;
double avg;
avg = getAverage(ptr, size);
cout << setprecision(2) << fixed << showpoint << endl;
cout << "The average is " << avg << endl;
return 0;
}
double getAverage(int *ptr, int size)
{
double average1;
double total = 0;
for (int count = 0; count < size; count++)
{
total = total + *(ptr + count);
}
average1 = total / size;
return average1;
}
우선 함수 getAverage()
에는 정의한 것과 다른 프로토 타입이 있습니다. 그리고 둘째로 당신은 통과하려고 std::unique_ptr<int []>
대신 예상하는 함수에 객체를 int*
. 그러나 암시 적으로 변환 할 수없는 std::unique_ptr<int []>
다른 유형 int*
입니다. 그래서 int *
사용 std::unique_ptr::get
기능 을 전달 합니다. 처럼
#include <iostream>
#include <iomanip>
#include <memory>
using namespace std;
double getAverage(int *, int);
int main()
{
int size = 0;
cout << "How many scores will you enter? ";
cin >> size;
unique_ptr<int[]> ptr(new int[size]);
cout << endl;
int count = 0;
//gets the test scores
for (count = 0; count < size; count++)
{
cout << "Enter the score for test " << (count + 1) << ": ";
cin >> ptr[count];
cout << endl;
}
//display test scores
cout << "The scores you entered are:";
for (count = 0; count < size; count++)
cout << " " << ptr[count];
cout << endl;
double avg;
avg = getAverage(ptr.get(), size);
cout << setprecision(2) << fixed << showpoint << endl;
cout << "The average is " << avg << endl;
return 0;
}
double getAverage(int *ptr, int size)
{
double average1;
double total = 0;
for (int count = 0; count < size; count++)
{
total = total + *(ptr + count);
}
average1 = total / size;
return average1;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다