首页 > 解决方案 > 程序在 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;
}

标签: c

解决方案


您没有正确打印结果:

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

to的第一个参数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);

推荐阅读