gpt4 book ai didi

c - 只是想知道我的代码 C 编程到底出了什么问题

转载 作者:行者123 更新时间:2023-11-30 21:31:26 26 4
gpt4 key购买 nike

我不知道我的代码出了什么问题,我正在使用 Visual Studio,它说我没有标识符,我不能 100% 确定这意味着什么,我基本上必须为 pow 编写一个新函数,我不太明白太多了,但是如果有人可以看看我的代码,那将会非常有帮助,谢谢

// Programmer:     Your Name
// Date: Date
// Program Name: The name of the program
// Chapter: Chapter # - Chapter name
// Description: 2 complete English sentences describing what the program does,
// algorithm used, etc.
#define _CRT_SECURE_NO_WARNINGS // Disable warnings (and errors) when using non-secure versions of printf, scanf, strcpy, etc.
#include <stdio.h> // Needed for working with printf and scanf
#include <math.h>
#include <string.h>

int main(void)
{
// Constant and Variable Declarations
double power(double num, int power) {
double result = 1;
if (power > 0) {
int i = 0;
for (i = 0; i < power; i++) {
result *= num;
}
return result;
}
else {
if (power < 0) {
power *= -1;
int i = 0;
for (i = 0; i < power; i++) {
result *= num;
}
}
return 1 / result;
}
}
int main(void)
{
double number;
int p;
printf("Enter a number to raise to a power : ");
scanf("%lf", &number);
printf("Enter the power to raise %.2lf to : ", number);
scanf("%d", &p);
printf("%.2f raised to the power of %d is : ", p);
double result = power(number, p);
double mathPow = pow(number, p);
printf("\n%-20s%-20s\n", "My Function", "Pow() Function");
printf("%-20.2f%-20.2f\n", result, mathPow);
return 0;
}
// *** Your program goes here ***
return 0;
} // end main()

最佳答案

您不能(或者至少不应该)在 C 语言的函数内定义函数。

cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic -g `pkg-config --cflags glib-2.0`   -c -o test.o test.c
test.c:15:41: error: function definition is not allowed here
double power(double num, int power) {
^
test.c:36:5: error: function definition is not allowed here
{
^

并且您有两个 main 函数。 main 是程序运行时由操作系统运行的函数。您只需要一个。

还有一些其他问题...

test.c:41:52: warning: format specifies type 'double' but the argument has type 'int' [-Wformat]
printf("%.2f raised to the power of %d is : ", p);
~~~~ ^
%.2d
test.c:41:42: warning: more '%' conversions than data arguments [-Wformat]
printf("%.2f raised to the power of %d is : ", p);

那个printf缺少参数。应该是...

printf("%.2f raised to the power of %d is : ", number, p);

通过这些修复,它可以正常工作。

<小时/>

您可以DRY通过定义仅用于正数的第二个函数来提高功率

double power_positive(double num, int power) {
int i = 0;
double result = 1;
for (i = 0; i < power; i++) {
result *= num;
}
return result;
}

double power(double num, int power) {
if (power < 0) {
return 1 / power_positive(num, -power);
}
else {
return power_positive(num, power);
}
}

关于c - 只是想知道我的代码 C 编程到底出了什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53252397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com