第十二周项目一(4)

本文详细解析了C++中默认参数的使用方法及其常见错误,并通过实例展示了如何正确设置默认参数以避免常见错误,对于提高编程效率和代码可读性具有重要意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码

#include <iostream>
using namespace std;
const double pi=3.1415926;
float area(float r=6.5);//指定r的默认值为6.5
float volume(float h,float r=6.5); //指定r的默认值为6.5
int main( )
{
    cout<<area()<<endl; //相当于area(6.5);
    cout<<area(7.5)<<endl; //形参得到的值为7.5,而不是6.5
    cout<<volume(45.6)<<endl; //相当于volume(45.6,6.5)
    cout<<volume(34.2,10.4)<<endl; //h的值为34.2,r的值为10.4
    return 0;
}
float area(float r)
{
    return pi*r*r;
}
float volume(float h,float r)
{
    return pi*r*r*h;
}


总结:去掉4 行“=6.5”。我的原因是8行调用时出错,r无输入值。

            \main.cpp|8|error: too few arguments to function 'float area(float)'|
            \main.cpp|4|note: declared here|
           ||=== Build finished: 1 errors, 0 warnings (0 minutes, 2 seconds) ===|

          14行'|改为r=6,5,我以为错在不能赋值。

           \main.cpp|4|error: expected ',' or '...' before numeric constant|
            \main.cpp||In function 'int main()':|
              \main.cpp|8|error: too few arguments to function 'float area(float)'|
                \main.cpp|4|note: declared here|
                  ||=== Build finished: 2 errors, 0 warnings (0 minutes, 1 seconds) ===|

        将第5行改为“float h=1,float r”,我以为10行会出错,r无值。

        \main.cpp|4|error: expected ',' or '...' before numeric constant|
         \main.cpp|5|error: default argument missing for parameter 2 of 'float volume(float, float)'|
          \main.cpp||In function 'int main()':|
           \main.cpp|8|error: too few arguments to function 'float area(float)'|
            \main.cpp|4|note: declared here|
              ||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|

       将第5行改为“float volume(float h=0,float r=6.5)”,不会有影响

     

总结:通过这个练习,对默认参数的用法及作用有了更深刻的认识

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值