「已注销」 2015-06-13 00:57 采纳率: 33.3%
浏览 1671
已采纳

c++初学者一枚,希望有好心人能够帮我解答这行代码的意思

该题为c++ primer plus 书籍中 第七章课后习题

这个double * fill_array(double *pfirst, double *pend)函数体中,
最后的return 返回了一个 --ptemp; 为什么要反回这个,这个位置有点看不懂,反回--ptemp是反回的什么东西?指针地址的自减吗?
另外: if (!cin) // bad input
{

cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
if(i == 0)
return ptemp;
else
return --ptemp;
}

这里也有 return --ptemp; 希望能有朋友帮我解答疑惑,感激不尽,为何要反回这个呢!

#include
const int Max = 5;

// function prototypes
double * fill_array(double *pfirst, double *pend);
void show_array( double *pfirst, double *pend);
void revalue(double *pfirst, double *pend, double r);

int main()
{
using namespace std;
double properties[Max];

double  *pos = fill_array(properties, properties+(Max-1));
show_array(properties, properties+(Max-1));
cout << "Enter revaluation factor: ";
double factor;
cin >> factor;
revalue(properties, properties+(Max-1), factor);
show_array(properties, properties+(Max-1));
cout << "Done.\n";
return 0;

}

double * fill_array(double *pfirst, double *pend)
{
using namespace std;
double temp;
double * ptemp;
int i = 0;

for (ptemp = pfirst; ptemp <= pend; ptemp++)
{
    cout << "Enter value #" << (i + 1) << ": ";
    cin >> temp;

    if (!cin)    // bad input
    {   
        cin.clear();
        while (cin.get() != '\n')
            continue;
       cout << "Bad input; input process terminated.\n";
       if(i == 0)
           return ptemp;
       else 
           return --ptemp;
    }
    else if (temp < 0)     // signal to terminate
        break;
    pfirst[i] = temp;
    i++;
}
return --ptemp;

}

// the following function can use, but not alter,
// the array whose address is pfirst
void show_array( double *pfirst, double *pend)
{
using namespace std;
double * ptemp;
int i = 0;
for (ptemp = pfirst; ptemp <= pend; ptemp++,i++)
{
cout << "Property #" << (i + 1) << ": $";
cout << *ptemp << endl;
}
}

// multiplies each element of ptemp by r
void revalue(double *pfirst, double *pend, double r)
{
double *ptemp;
for (ptemp = pfirst; ptemp <= pend; ptemp++)
*ptemp *= r;
}

  • 写回答

7条回答

  • devmiao 2015-06-13 01:12
    关注

    就你的代码来说
    return --ptemp;

    return ptemp - 1;
    没有区别
    这里返回的是数组最后一个元素的地址。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀