gpt4 book ai didi

C关于函数

转载 作者:行者123 更新时间:2023-11-30 19:13:09 25 4
gpt4 key购买 nike

我是编程新手,正在尝试编写一个具有 3 个函数的程序,要求用户输入 c 表示圆或 t 表示直角三角形。然后输入半径(如果是c)或两条边(如果是三角形)。我在使用 display 函数时遇到问题,它在两种情况下都将答案打印为 0 。如果我在圆形或三角形函数内输入 printf 语句,它会正确打印,但我需要函数 display。这是我的代码。任何见解将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define M_PI 3.14

void circle(int num, double area, double per) {
area = (double)(M_PI * pow(num, 2));
per = (double)(2 * M_PI * num);
}

void rt(int num, int num1, double area, double per) {
area = (double)(0.5 * num * num1);
per = (double)((num + num1) + sqrt(pow(num, 2) + pow(num1, 2)));
}

void display(char entry, double area, double per) {
if (entry == 'c') {
printf("The circle has area %.1lf and perimeter %.1lf.\n", area, per);
} else {
printf("The right triangle has area %.1lf and perimeter %.1lf.\n", area, per);

}
}

int main() {
char entry;
int num;
int num1;
double area = 0;
double per = 0;

printf("Please enter 'c' for a circle or 't' for a right triangle\n");
scanf("%c", &entry);
if (entry == 'c') {
printf("Please enter the radius for the circle.\n");
scanf("%d", &num);
getchar();
circle(num, area, per);
} else
if (entry == 't') {
printf("Please enter the length of two sides.\n");
scanf("%d %d", &num, &num1);
getchar();
rt(num, num1, area, per);
} else {
printf("Invalid input!");
}

display(entry, area, per);
return 0;
}

最佳答案

您的circlert函数只是更新它们的参数,而不是main中的局部变量。您必须将指针传递给 circlert 来更新它们。

这是更正后的版本:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void circle(int num, double *area, double *per) {
*area = M_PI * pow(num, 2);
*per = 2 * M_PI * num;
}

void rt(int num, int num1, double *area, double *per) {
*area = 0.5 * num * num1;
*per = (num + num1) + sqrt(pow(num, 2) + pow(num1, 2));
}

void display(char entry, double area, double per) {
if (entry == 'c') {
printf("The circle has area %.1lf and perimeter %.1lf.\n", area, per);
} else {
printf("The right triangle has area %.1lf and perimeter %.1lf.\n", area, per);

}
}

int main() {
char entry;
int num, num1;
double area = 0;
double per = 0;

printf("Please enter 'c' for a circle or 't' for a right triangle\n");
scanf("%c", &entry);
if (entry == 'c') {
printf("Please enter the radius for the circle.\n");
scanf("%d", &num);
getchar();
circle(num, &area, &per);
} else
if (entry == 't') {
printf("Please enter the length of two sides.\n");
scanf("%d %d", &num, &num1);
getchar();
rt(num, num1, &area, &per);
} else {
printf("Invalid input!\n");
}
display(entry, area, per);
return 0;
}

关于C关于函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35856113/

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