【问题标题】:How to efficiently find the sum of (1/a^2x) without using the power function? [closed]如何在不使用幂函数的情况下有效地找到 (1/a^2x) 的总和? [关闭]
【发布时间】:2022-06-26 08:03:16
【问题描述】:

我需要在 C 编程语言中计算数字 a (double) 到 n (int) 的幂的总和。没有pow 功能!

我已经这样做了,但它非常复杂,我想要更简单的东西。

如果您知道如何通过 Java 或 C++ 或 Pascal 进行此操作,请也回复)

1/a2 + 1/a4 + 1/a6 ... + 1/a2n。

program sum;
 
var i, n: integer;
    s, a, x: real;
    f: boolean;
 
begin
  repeat
    write(\'n = \'); readln(n);
    if n < 1 then writeln(\'Error: n <= 0, reenter.\')
  until n >= 1;
  repeat
    write(\'a = \'); readln(a);
    if a = 0 then writeln(\'Error: a = 0, reenter.\')
  until a <> 0;
  s := 0;
  x := 1;
  f := true;
  for i := 1 to n do
    begin
      x := x / a / a;
      if x = 0
        then begin
          writeln(\'Float rounding error.\');
          f := false;
          break
        end;
      s := s + x
    end;
  if f then writeln(\'s = \', s);
  readln
end;
  • 我投票结束这个问题,因为它是关于应该通过阅读 C 入门或教科书并完成课程作业而不是通过 Stack Overflow 提问来学习的基本材料。
  • 在我看来,这更像是pascal
  • \“如果你知道如何通过 Java、C++ 或 Pascal 制作这个,请也回复一下\”欢迎来到 Stack Overflow。请阅读How to Ask 并注意这是不是讨论区.我们期待一个具体的问题,其中包括 - 除其他事项外 - 您选择一种实现语言并坚持使用它,除非您通常在寻找一种算法。有一个language-agnostic 标签,但类似的问题通常更适合Computer Science。 \“我已经这样做了,但它非常复杂,我想要更简单的东西。\”请尝试Code Review 来回答这类问题。

标签: pascal


【解决方案1】:

在 C 中:

double bPow = 1;
double sum = 0
double b = a * a;

for (int i = 0; i < n; i++)
{
    bPow *= b;
    sum += 1 / bPow;
}

这为您提供了 x = [2, 4, ..., 2n] 的所有 1/a^x 的总和。

【讨论】:

    【解决方案2】:

    更简单的方法是使用 while 循环。 这里我使用 sum 为s,base 为b,power 为p

    C语言程序:

    #include <stdio.h>
    
    void main() {
        
        int s=1, b, p;
        
        printf("\nEnter the base value :");
        scanf("%i",&b);
        
        printf("\nEnter the power value :");
        scanf("%i",&p);
        
        while( p != 0)
        {
            s = s * b;
            
            p--;
        }
        
        printf("\nThe Sum  : %i", s);
        
        getch();
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-13
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多