c - 程序在C中无限运行,在编译或运行时没有错误

标签 c

这是我用 C 编写的第一个程序,所以请耐心等待! 我编写这段代码是为了计算一个基数乘以另一个给定数。我没有遇到编译错误,除了运行代码时没有任何反应。我究竟做错了什么?

谢谢!

#include <stdio.h>
#include <stdlib.h>

int expCalculator(int base, int exponent) {
    if (exponent == 0){
        return 1;
    }
    else if (exponent % 2) {
        return base * expCalculator(base, exponent - 1);
    }
    else {
        int temp = expCalculator(base, exponent / 2);
        return temp * temp;
    }
}

int main() {
    float base, answer;
    int exponent;
    int positiveBase;
    char buffer[10];

    positiveBase = 0;
    while (positiveBase == 0){
        printf("Enter a base number: ");
        scanf(" %f", &base);
        if (base > 0){
            positiveBase = 1;
            printf("Please enter an exponent value to raise the base to: ");
            scanf(" %d", &exponent);
            answer = expCalculator(base, abs(exponent));
            gcvt(base, 10, buffer);
            printf(buffer, " to the power of ", exponent, " is ", answer);
        }
        else {
          printf("Please enter a positive base! Try again.");
        }
    }
    return 0;
}

最佳答案

您没有正确打印结果:

printf(buffer, " to the power of ", exponent, " is ", answer);

printf 的第一个参数是格式字符串,后面的参数是适合该格式字符串的值。在这种情况下,编译器不会抛出任何警告,因为第一个参数的类型正确,其余的是变量参数。

许多编译器根据给定的格式字符串检查这些参数,但在本例中不会发生这种情况,因为格式字符串不是字符串常量。唯一打印的是 buffer,它被 base 转换为字符串。

你想要的是:

printf("%.10f to the power of %d is %f\n", base, exponent, answer);

请注意,这会直接使用格式字符串打印 base,因为 gcvt 函数已过时。

至于为什么您在终端中看不到任何内容,可能是由于缓冲所致。您打印的提示不包含换行符,因此输出缓冲区不一定会被刷新。您需要手动执行此操作:

printf("Please enter an exponent value to raise the base to: ");
fflush(stdout);

关于c - 程序在C中无限运行,在编译或运行时没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767600/

相关文章:

c - C 程序在 if 语句之前关闭

c - 如何将一些方程作为用户输入?

c - 同步udp广播文件传输

c - VS2013中一条语句中多个指针增量的解决方法

指针调用和值调用 C

c - 如何找到指向字符串的指针数组的新大小

c - 为 CUDA 编译 Hello world 程序时出错

c - 如何添加矩阵的对角线和半对角线

c - 退出阻塞的 recv() 调用

c - 如何完全而不是部分地将特定数量的字节写入/发送到套接字?