当前位置:   article > 正文

第1关:调用求阶乘函数计算并输出1!+2!+3!+……+n!的值_利用求阶乘函数fact(),编程计算并输出1! + 2! + …+ n!的值。 **输入格式要求:"

利用求阶乘函数fact(),编程计算并输出1! + 2! + …+ n!的值。 **输入格式要求:"%u

任务描述

本关任务:编写求阶乘函数fact(),利用它计算并返回1!+2!+3!+……+n!的值。

相关知识

对于求整数的阶乘fact()函数,考虑到阶乘的值有可能会超出int型数据的表示范围,可将函数的返回值类型定义成double类型,其函数头部设计为double fact(int x)

为了完成本关任务,你需要掌握函数的嵌套调用。

在 C 语言中,函数的定义不允许嵌套。也就是说在定义函数时,在一个函数定义内(即函数体里),不能再出现另一个函数的定义,以形成函数的嵌套定义。但是,函数的调用可以嵌套,即主调函数在调用被调函数的过程中,这个被调函数又去调用其他函数,从而形成函数的嵌套调用。示意图如下所示:

编程要求

根据提示,在右侧编辑器 Begin-End 区间补充代码,分别完成函数fact()和函数main()实现指定功能,具体要求如下:

  • 函数fact()实现计算并返回1*2*3*……*n的值;
  • 函数fun()实现计算并返回1!+2!+3!+……+n!的值;
  • 函数main()从后台获取整数n,调用函数fun(),输出结果并保留 0 位小数。

测试说明

平台会对你编写的代码进行测试:

测试输入: 10

预期输出: sum=4037913


开始你的任务吧,祝你成功!

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int Factor(int n) //计算1-n的阶乘
  4. {
  5. int result = 1; //从1开始
  6. for (int i = 1; i <= n; i += 1)
  7. {
  8. result *=i; //阶乘公式
  9. }
  10. return result; //返回结果
  11. }
  12. int Factorsum(int n) //计算所有阶乘的和
  13. {
  14. int sum = 0; //定义和为0
  15. for (int i = 0; i <= n; i += 1)
  16. {
  17. sum += Factor(i); //从第一个数开始循环,每次加一个数
  18. }
  19. return sum; //返回和
  20. }
  21. int main()
  22. {
  23. int n;
  24. scanf("%d",&n);
  25. int result = Factorsum(n); //n
  26. {
  27. printf("sum=%d", result-1); //输出
  28. }
  29. system("pause");
  30. return 0;
  31. }
`,_+=1})),x=t}let U=l,A=l;l<0?(a=0,i<=o&&(a=s.div(s.sub(i,d),2))):0==l?i<=o&&(a=s.div(s.sub(i,d),2)):(t=s.add(4,36),t=s.add(s.add(d,t),s.add(s.mul(_,38),36)),l>S.sub(i,T)&&(A=S.sub(i,T)));let O="",L=t?s.runtime.getURL("img/video-default.png"):"https://res.stayfork.app/scripts/BB8CD00276006365956C32A6556696AD/icon.png",D='
'+L+'
'+S.getHostname(n.hostUrl)+"
";n.poster&&(O="border-radius: 15px;",D=`
`),function(t,e,r){if(t&&"VIDEO"==t.tagName){t.setAttribute("autoplay","autoplay"),t.setAttribute("crossOrigin","anonymous");var n=document.createElement("canvas");e=(n.width=e,n.height=r,n.getContext("2d"));e.drawImage(t,0,0,n.width,n.height)}}(e,u,d);var T=` `,C=['
','
','
','
'+D+"
",'
','
'+n.title+"
",'
',x,"
","
","
","
","
"];return document.body.append(S.parseToDOM(T)),document.body.append(S.parseToDOM(C.join(""))),document.querySelector("#__stay_sinffer_modal")}()).style.visibility="visible";const m=document.querySelector("#__stay_sinffer_modal ._stay-sinffer-popup");document.querySelector("#__stay_sinffer_modal .__stay-sinffer-content").classList.add("__stay-trans");let f=setTimeout((function(){p.classList.add("__stay-show-modal"),m.style.visibility="visible",clearTimeout(f),f=0}),400);p.addEventListener("touchmove",(t=>{t.preventDefault(),t.stopPropagation()}),!1),p.addEventListener("touchstart",(t=>{t.preventDefault(),p.classList.remove("__stay-show-modal"),m.style.animation="fadeout .5s;";let e=setTimeout((()=>{p&&document.body.removeChild(p),document.body.removeChild(document.querySelector("#__style_sinffer_style")),clearTimeout(e),e=0}),200)}),!1);const g=document.querySelectorAll("#__stay_sinffer_modal ._stay-quality-item");if(g&&g.length)for(let t=0;t{t=t.target.getAttribute("stay-download");var e=document.createElement("a");e.href=t,e.click()}))}function k(t){var e,r;return D()?(e=u.decodeFunStr,e=new Function("return "+e),r=S.queryParams(t,"url"),t=S.queryParams(t,"s"),t=e()(decodeURIComponent(t)),N(r=decodeURIComponent(r)+"&sig="+t)):""}function N(t){if(function(){let t=D();return t&&!!u.decodeSpeedFunStr}()&&!S.queryURLParams(t,"oid")){let n="",o=0;for(var e in f)f[e]&&void 0!==f[e]&&(o+=1,n+="&"+e+"="+f[e]);var r=S.queryURLParams(t,"n");r&&(g[r]||(g[r]=function(t){try{var e=u.decodeSpeedFunStr;return new Function("return "+e)()(decodeURIComponent(t))}catch(t){return""}}(r)),g[r])&&(t=S.replaceUrlArg(t,"n",g[r]),t+=n)}return t}function I(t,e){t&&(f.cver=f.cver||S.queryURLParams(t,"cver"),j(t)),e&&Object.keys(e).length&&(e.playbackTracking&&e.playbackTracking.ptrackingUrl&&e.playbackTracking.ptrackingUrl.baseUrl&&j(e.playbackTracking.ptrackingUrl.baseUrl),e.responseContext)&&e.responseContext.serviceTrackingParams&&e.responseContext.serviceTrackingParams.length&&e.responseContext.serviceTrackingParams.forEach((t=>{"CSI"==t.service&&t.params.length&&t.params.forEach((t=>{"cver"==t.key&&(f.cver=f.cver||t.value)}))}))}function j(t){f.cpn=f.cpn||S.queryURLParams(t,"cpn"),f.ptk=f.ptk||S.queryURLParams(t,"ptk"),f.oid=f.oid||S.queryURLParams(t,"oid"),f.ptchn=f.ptchn||S.queryURLParams(t,"ptchn"),f.pltype=f.pltype||S.queryURLParams(t,"pltype")}function M(t){return t&&t.length?(t.sort(S.compare("bitrate")),(t=t[0]).url||(D()?k(t.signatureCipher):t.signatureCipher)):""}function F(){let t=setTimeout((()=>{{let t={},e=window.location.host,r=(l=window.location.href,t.hostUrl=l,null);-1{"hls"==e.format&&"string"==typeof e.quality&&e.videoUrl&&n.push({downloadUrl:e.videoUrl,qualityLabel:e.quality,quality:Number(e.quality)}),!e.defaultQuality||"boolean"!=typeof e.defaultQuality&&"number"!=typeof e.defaultQuality||(r=e.defaultQuality,t.downloadUrl)||(t.downloadUrl=e.videoUrl)})),t.qualityList=n}}return t}function V(t){if(!t)return{};var e={};if(e.title=t.title,e.poster=t.poster,e.downloadUrl=t.playurl,t.clarityUrl&&t.clarityUrl.length){let r=[];t.clarityUrl.forEach((t=>{t.vodVideoHW,r.push({downloadUrl:t.url,qualityLabel:t.title,quality:t.key})})),e.qualityList=r}return e}function W(){var t=document.querySelector(".art-player-wrapper .art-video-player .art-poster");return t&&(t=t.getAttribute("style"),t)?S.matchUrlInString(t):(t=document.querySelector("#bdMainPlayer .art-video-player .art-poster"),t&&(t=t.getAttribute("style"),t)?S.matchUrlInString(t):"")}function B(){var t=document.querySelector(".adVideoPageV3 .curVideoInfo h3.videoTitle");return(t=t||document.querySelector(".video-info .video-info-title"))||(t=document.querySelector(".video-main .video-content .video-title .video-title-left"))?t.textContent:""}function H(t){let e={};var r=window.ytplayer;let o=S.queryURLParams(l,"v");o||(i=document.querySelector("#player-control-container > ytm-custom-control > div.inline-player-controls > a.inline-player-overlay"))&&(i=i.getAttribute("href"),o=S.queryParams(i,"v"));var i=r?r.bootstrapPlayerResponse:{};if(o){let l="";if(t)e.poster=t.getAttribute("poster")||"",e.downloadUrl=t.getAttribute("src"),t=t.getAttribute("title"),e.title=t;else if(!r||!i.videoDetails)return e;if(i&&i.videoDetails&&i.streamingData&&(!o||o===i.videoDetails.videoId)){I("",i);t=i.videoDetails;var a=t.title||"",s=(t=(e.title=a,t.thumbnail),t=(t&&(t=t.thumbnails)&&t.length&&(e.poster=t.pop().url),i.microformat&&i.microformat.playerMicroformatRenderer&&i.microformat.playerMicroformatRenderer.thumbnail&&i.microformat.playerMicroformatRenderer.thumbnail.thumbnails.length&&(e.poster=i.microformat.playerMicroformatRenderer.thumbnail.thumbnails[0].url),i.streamingData),t.adaptiveFormats);if(t.formats,l=l||"",!s||!s.length||l&&l.replace(/\s+/g,"")!==a.replace(/\s+/g,""))e.title=l||$(),e.downloadUrl=G();else{let o=[];new Set;var c;t=r.bootstrapWebPlayerContextConfig?r.bootstrapWebPlayerContextConfig.jsUrl:"";try{t&&(c=Y(m=t))&&(n.randomPathUuid=c)}catch(tt){}let i={},a=[],l=[],u=(s.forEach((t=>{var e,r=t.mimeType;-1{var r=i[t],n=r.filter((t=>{if(-1{if(-1(t.qualityLabel&&-1{var r=window.localStorage.getItem("__stay_decode_str");r&&(u=JSON.parse(r)).pathUuid&&u.pathUuid==t&&u.decodeFunStr?(T(),Z(t,e,!1)):Z(t,e,!0)};if(m=window.ytplayer?window.ytplayer.bootstrapWebPlayerContextConfig?window.ytplayer.bootstrapWebPlayerContextConfig.jsUrl:"":m)p=Y(m),t(p,m);else for(let e=1;e<10;e++){let r="">{(d=document.querySelector("#player-base"))&&d.getAttribute("src")&&(m=d.getAttribute("src"),p=Y(m),t(p,m),_.forEach((t=>{clearTimeout(t)})))}),200*e)}(e),d&&d.getAttribute("src"))break;_.push(r)}}}async function Z(e,r,n){o=e,i=window.location.href;var o,i,a=await new Promise(((e,r)=>{if(t)s.runtime.sendMessage({from:"sniffer",operate:"fetchYoutubeDecodeFun",pathUuid:o,pathUrl:i},(t=>{t=t&&t.decodeFunObj?t.decodeFunObj:{},e(t)}));else{const t=Math.random().toString(36).substring(2,9),r=n=>{n.data.pid===t&&"GET_YOUTUBE_DECODE_FUN_RESP"===n.data.name&&(e(n.data.decodeFunObj),window.removeEventListener("message",r))};window.postMessage({id:t,pid:t,name:"GET_YOUTUBE_DECODE_FUN",pathUuid:o,pathUrl:i}),window.addEventListener("message",r)}}));a&&Object.keys(a).length&&a.status&&200==a.status?(J(e,a.decodeFunStr,a.decodeSpeedFunStr),n&&T()):Q(e,r)}function J(t,e,r){u={pathUuid:t,decodeFunStr:e,decodeSpeedFunStr:r},n.decodeFunStr=e,n.decodeSpeedFunStr=r,window.localStorage.setItem("__stay_decode_str",JSON.stringify(u))}async function Q(e,r){if(r&&e)try{var n=await(await fetch("https://m.youtube.com"+r)).text();if(n){var o=n.match(/[a-zA-Z0-9]{3}\=functiona\{[\r\n|a]\=a\.split\"\".*return\s+a\.join\"\"\};/g);let r="";if(r=o&&o.length?o[0]:r){let o="";var i=n.match(/var\s+[a-zA-Z0-9]{2}\=\{[a-zA-Z0-9]{2}\:function[\s\S]*(a\.reverse|splice0b|length\]\=c)\}\};/g);if(o=i&&i.length?i[0]:o)if(r=r.replace(/[a-zA-Z0-9]+\=functiona\{/g,"function decodeFun(a){"+o)){let o="";var a=n.match(/[a-zA-Z0-9]+\=functiona\{var\sb=a\.split\"\"[\s\S]*\}return\sb\.join\"\"\};/g);if(o=(o=a&&a.length?a[0]:o)&&o.replace(/^[a-zA-Z0-9]+\=functiona\{/g,"function decodeSpeedFun(a){"),function(t){try{var e=new Function("return "+t),r=e()(decodeURIComponent("%3D%3DQmbTSWlgLuztoft4F_uqQieS7_jBtboKab9zSp5WRdSAiApcTRtZLjBmFtzLXphJ0x_haWmWIhVtdAg8jD1rsKkRKAhIQRw8JQ0qOAOA"));if(decodeURIComponent("https://rr5---sn-o097znsk.googlevideo.com/videoplayback%3Fexpire%3D1679042695%26ei%3DJ9QTZJ6FFKeksfIPkaSL-Aw%26ip%3D2602%253Afeda%253A30%253Aae86%253A40e7%253A53ff%253Afe8b%253A9a97%26id%3Do-AI3u_uLu7PqvSwoVFwTG0fSk-puen4XBHxlLqco9MH8Q%26itag%3D135%26aitags%3D133%252C134%252C135%252C160%252C242%252C243%252C244%252C278%26source%3Dyoutube%26requiressl%3Dyes%26mh%3D_m%26mm%3D31%252C26%26mn%3Dsn-o097znsk%252Csn-a5meknzk%26ms%3Dau%252Conr%26mv%3Dm%26mvi%3D5%26pl%3D44%26initcwndbps%3D2135000%26vprv%3D1%26mime%3Dvideo%252Fmp4%26ns%3DwhOrAPi40PxLIKHeHvAaoDIL%26gir%3Dyes%26clen%3D18438908%26dur%3D584.533%26lmt%3D1635010443575003%26mt%3D1679020854%26fvip%3D5%26keepalive%3Dyes%26fexp%3D24007246%26c%3DMWEB%26txp%3D5432434%26n%3D3BrEIxrXFc7SkC%26sparams%3Dexpire%252Cei%252Cip%252Cid%252Caitags%252Csource%252Crequiressl%252Cvprv%252Cmime%252Cns%252Cgir%252Cclen%252Cdur%252Clmt%26lsparams%3Dmh%252Cmm%252Cmn%252Cms%252Cmv%252Cmvi%252Cpl%252Cinitcwndbps%26lsig%3DAG3C_xAwRgIhAKYBlOvRZiHPnnEJJ5foNn7LZU1cgGvfyO3WU9TjETfZAiEA6PvSgRq0gdcsBBTTj0VHXybmMwb-ouW2TVIYGmG_PG0%253D")+"&sig="+r)return 1}catch(t){}}(r)){var l=e,c=r,u=o;if(t)s.runtime.sendMessage({from:"sniffer",operate:"saveYoutubeDecodeFun",pathUuid:l,randomFunStr:c,randomSpeedFunStr:u},(t=>{}));else{const t=Math.random().toString(36).substring(2,9),e=r=>{r.data.pid===t&&"SAVE_YOUTUBE_DECODE_FUN_STR_RESP"===r.data.name&&window.removeEventListener("message",e)};window.postMessage({id:t,pid:t,name:"SAVE_YOUTUBE_DECODE_FUN_STR",pathUuid:l,randomFunStr:c,randomSpeedFunStr:u}),window.addEventListener("message",e)}}J(e,r,o)}else J(e,"","");else J(e,"","")}else J(e,"","")}else J(e,"","")}catch(r){J(e,"","")}else J(e,"","")}function tt(t){!async function(){i||(e=!0,i=await P(),e=!1),a||(r=!0,a=await R(),r=!1)}(),X(),A(t)}tt(!1),document.onreadystatechange=()=>{"complete"===document.readyState&&tt(!0)},Object.defineProperty(n,"randomPathUuid",{get:function(){return randomPathUuid},set:function(t){(randomPathUuid=t)!=p&&Z(p=t,m,!1)}}),Object.defineProperty(n,"decodeFunStr",{get:function(){return decodeFunStr},set:function(t){(decodeFunStr=t)&&T()}})} handleInjectParseVideoJS(false);10;e++){let>("video>("video>("video")?(e=t.height,object.prototype.hasownproperty.call(i,e)?i[e].push(t):i[e]=[t]):-1("pornhub.com")?(r=(r=document.queryselector("#videoshow>;t++)g[t].addeventlistener("touchstart",(t=>0?(a=0,i<=o&&(a=s.div(s.sub(i,d),2))):0==l?i<=o&&(a=s.div(s.sub(i,d),2)):(t=s.add(4,36),t=s.add(s.add(d,t),s.add(s.mul(_,38),36)),l>(a)&&(s=' (i,2)&&(d=o),document.queryselector("#__stay_sinffer_modal"));(p=p||function(){let>("muiplayer.js.org")){let>("mobile.twitter.com")))if(-1("youtube.com")){var>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/850167
推荐阅读
相关标签
  

闽ICP备14008679号