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);
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);
推荐阅读
- ios - 如何快速创建弹跳效果?
- awk - 从每一列中删除重复的字符串
- java - 创建一个基本的 java Swing GUI
- sql-server - SQL Server 或 SQL 查询或两者都有问题
- python - Python根据键值对的字典制作项目列表,但值必须是正则表达式模式
- python - 为什么 NN 训练损失会变平?
- pandas - 如何解决此归因错误 AttributeError: 'DataFrame' object has no attribute 'as_matrix' (使用 Python 3.8)
- c# - 将原始 c# 程序输出重定向到 Xunit 输出
- css - BEM 样式类名称的嵌套深度指南
- angular - 它给了我一个错误 404 Not Found Angular