c - 如果没有 printf,For 循环将无法工作

标签 c for-loop

我有两个问题。

我想编写一个函数来求解方程:

int equation() {
    int n, r, s;

    printf("\nEnter the value of N: ");
    scanf("%d", &n);

    printf("Enter the value of R: ");
    scanf("%d", &r);

    printf("Enter the value of S: ");
    scanf("%d", &s);

    int i, j, k;
    int c = 0;
    int a[r], b[s];

    a[0] = 1;
    for (i = 1; i <= r; i++) {
        a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));
    }

    for (j = 1; j <= s; j++) {
        b[j] = b[j-1] + sqrt(3 * (j * j * j) + j + 2) / (2 * j);
    }
    // The last for loop
    for (k = 1; k <= n; k++) {
        c += a[k] / b[k];
    }

    printf("Result: %d \n \n", c);

    return c;
}

如果最后一个 for 循环中包含以下行,则效果很好:

printf("%d, %d, %d", c, a[k], b[k]);

但是如果最后一个没有上面的行,则返回0。可能是什么问题?

预期值:

n, r, s = 1 结果应为 8。

n, r, s = 2 结果应为 36。

n, r, s = 3 结果应为 204。

如果我将 printf 行写入最后一个 for,我会得到这些值。

我还想问一个问题。当我改变这一行时

a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));

到此

a[i] = a[i-1] * ((((pow(i, 3) * 3) + 5) / (i * i));

它给了我不同的结果。为什么?

谢谢。

最佳答案

整数算术与浮点算术。

第一个表达式 ((((i * i * i) * 3) + 5)/(i * i)) 使用整数算术,因此是整数除法。第二个表达式 ((((pow(i, 3)) * 3) + 5)/(i * i)),因为 pow() 被定义为返回double 将使用浮点算术进行计算,因此将返回浮点值。该值乘以整数 a[i-1] 可能会得到不同的结果,其本身会转换回 int 以存储到 a[i] 中.

第二个循环引用尚未初始化的b[0]。整个计算取决于该值,在此之前或之后更改代码可能会更改在没有任何初始化的情况下恰好存在的随机值,并导致代码看起来可以工作。将 b[0] 初始化为应有的值并再次运行测试。使用我的下面的版本和 double 算术来实现这一点。

对于您的问题,您应该使用 double 类型而不是 int 来表示 a[]b[]c,通过强制转换 (double) 将整数转换为 double 并使用浮点常量 3.05.0 强制浮点计算:

double equation(void) {
    int n, r, s;

    printf("\nEnter the value of N: ");
    if (scanf("%d", &n) != 1) return -1;

    printf("Enter the value of R: ");
    if (scanf("%d", &r) != 1) return -1;

    printf("Enter the value of S: ");
    if (scanf("%d", &s) != 1) return -1;

    if (r < n || s < n) {
        printf("Invalid values, N must be greater or equal to noth R and S\n");
        return -1;
    }

    int i, j, k;
    double c = 0.0;
    double a[r+1], b[s+1];

    a[0] = 1.0;
    for (i = 1; i <= r; i++) {
        a[i] = a[i-1] * (((((double)i * i * i) * 3.0) + 5.0) /
                         ((double)i * i));
    }

    b[0] = 1.0; // you forgot to initialize b[0], what should it be?
    for (j = 1; j <= s; j++) {
        b[j] = b[j-1] + sqrt(3.0 * ((double)j * j * j) + j + 2.0) / (2.0 * j);
    }

    // The last for loop
    for (k = 1; k <= n; k++) {
        c += a[k] / b[k];
    }

    printf("Result: %f\n\n", c);

    return c;
}

关于c - 如果没有 printf,For 循环将无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34255119/

相关文章:

c - 为什么 GCC 声明 clock_gettime() 隐式声明,但预处理器对相关宏非常满意?

c - 如何在 linux 内核模块中分配由 1GB HugePages 支持的 DMA 缓冲区?

c - OMP 对于并行线程 ID hello world

javascript - 我不明白为什么我的 for 循环返回 "undefined"

arrays - var array [rows] [columns] int在Go中将维度分配给数组

C: 为什么 fprintf(stdout,....) 这么慢?

c - 如何在 C 中将 4 个数字打印为字符串?

c - 通过 TCP 发送一个 int 数组时,为什么只有第一个数量是正确的?

python - 如何使用 Python REGEX 重新获得模式中的特定术语

java - 使用随机数调整整数数组的大小