这是我用 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/