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

  • 本文关键字:问题 编程 想知道 代码 c
  • 更新时间 :
  • 英文 :


我不知道我的代码出了什么问题,我正在使用visualstudio,它说我没有标识符,我不能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%-20sn", "My Function", "Pow() Function");
printf("%-20.2f%-20.2fn", 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 uppower

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);
}
}

最新更新