我写了一个程序来计算谐波系列的总和(1 + 1/2 + 1/3 .. + 1/n),但是我在编译它时遇到了麻烦.我多次查看代码但是我没有看到任何语法错误[当我尝试编译时出现2].我的逻辑错了,还是语法错误?
#include <stdio.h>
int main( void ) {
int v,p,i;
double x=0;
printf("Enter a value to calculate the value of this harmonic series: \n");
scanf("%d",&v);
if (v<=0) {
printf("Please enter a POSITIVE number: \n");
scanf("%d",&p);
while (i=1; i<=v; i++) {
x=x+(1/i); }
printf("The value for the series is %lf", x);
}
else {
while (i=1; i<=v; i++) {
x=x+(1/i);
}
printf("The value for the series is %lf", x);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
所有这些while应该是for,并且1/i应该是1./i或者1/(double)i,因为否则执行整数除法.此外,您应该重新构建程序流程以避免代码重复.
但是,有一个微妙但更重要的错误:由于浮点运算如何工作,你应该开始从较小的数字到大的数字之和,否则你可能达到这一点,每个新的加数小于当前的精度double,并且添加将无效1.所以,你for应该逆转:
for (i=v; i>=1; i--)
Run Code Online (Sandbox Code Playgroud)
另外:你应该检查返回值为scanf1,以确保用户实际插入了一些有效的数字输入.并且,s 的printf说明符double只是%f,没有l.
考虑到所有这些,您可以将程序重写为:
#include <stdio.h>
int main( void )
{
int v=0,i,ch;
double x=0.;
printf("Enter a value to calculate the value of this harmonic series: ");
/* The loop calls the scanf, and is repeated as far as the user continues to
write garbage */
while(scanf("%d",&v)==0 || v<=0)
{
printf("Please enter a POSITIVE number: ");
/* Empty the input buffer to remove the eventual garbage; the logic is
a bit convoluted to handle the case where the user enters EOF */
while((ch=getchar())!='\n')
if(ch==EOF)
return 1;
}
/* perform the actual sum - done from smallest to biggest term */
for (i=v; i>=1; i--)
x+=1./i;
printf("The value for the series is %f\n", x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我注意到一堆错误....
(1)第二次扫描,你将值放入p,但绝不使用p.因此,您将测试i <= v for v <= 0,因此'loop'(参见稍后)将不会运行
(2)当你在循环中使用'for'时,你使用'while'
(3)i是一个整数,所以1/i将评估为1(对于i = 1),或0.使1 /((double)i)或类似的东西.
可能会有更多.
| 归档时间: |
|
| 查看次数: |
4017 次 |
| 最近记录: |