2015-09-12 1 views
0

Я кодирую это с помощью C. Я пытаюсь заставить функцию pow работать над этой проблемой. используя базу в качестве переменной, которую вводит пользователь. Эта программа просит пользователя рассчитать площадь и затраты на простой открытый баннер. вот код:pow (user_inputed_data, 2) function in C

//Pre-processor Directives 
#include <stdio.h> 
#include <math.h> 
#define PI 3.14159 

//Start of function 
int main(void) 
{ 
    //Declared variables 
    float base_area, height_area, total_area_per_container; 
    float radius, height, cost_per_container, total_cost, cost_per_sq_cm; 
    int containers; 

    //user input 
    //radius input 
    printf("Enter radius of base in cm: "); 
    scanf("%f", &radius); 
    //height input 
    printf ("Enter height of container in cm: "); 
    scanf("%f", &height); 
    //material cost 
    printf("Enter material cost per square cm: "); 
    scanf(" $%f", &cost_per_sq_cm); 
    //amount of containers 
    printf("Enter the number of containers to be produced: "); 
    scanf("%d", &containers); 

    //calcualtions of each container 
    base_area = PI * pow(radius,2); 
    height_area = 2 * PI * radius * height; 
    total_area_per_container = base_area + height_area; 

    //calculation of the cost of the material 
    cost_per_container = total_area_per_container * cost_per_sq_cm; 
    total_cost = containers * cost_per_container; 

    //Print results 
    printf("Surface area of container: %.2f cm\n", total_area_per_container); 
    printf("Cost per container: $%.2f\n", cost_per_container); 
    printf("Total production costs: $%.2f\n", total_cost); 

    //exit program 
    return (0); 
} 

все работает нормально, если я вынимаю военнопленный (радиус, 2) при комментарии расчетах каждого контейнера и положить в «радиусе * радиус» Я просто хотел проверить, чтобы увидеть, как функция pow работает. Я чувствую, что делаю что-то неправильно. Также я использую NetBeans IDE 8.0.2 для написания кода.

Update1: использование компилятора gcc, который имеет мой инструктор. компиляции моего кода на своем компьютере, дает мне этот faling ответ:

первая часть является связкой jargin говоря я копируя свой код на свой компьютер, что следует есть в каталогах цен ниже мой материал хранится на удаляет

In function `main': 
undefined reference to `pow' 
collect2: error: ld returned 1 exit status 
gmake[2]: *** [dist/Debug/GNU-Linux-x86/hw5] Error 1 
gmake[2]: Leaving directory 
gmake[1]: *** [.build-conf] Error 2 
gmake[1]: Leaving directory 
gmake: *** [.build-impl] Error 2 

BUILD FAILED (exit value 2, total time: 2s) 
+2

'' определяет константу 'M_PI', которая должна использоваться вместо' PI'. – dasblinkenlight

+2

'pow (radius, 2)' в целом медленнее и менее точным, чем радиус радиуса –

+0

@ChrisBeck 'C' не поддерживает перегруженные функции. – DevNull

ответ

1

Компиляция не работает, поскольку вы не связываетесь с математической библиотекой. Попробуйте компилировать с помощью:

gcc infile.c -lm 

Во-вторых, в вашем коде есть глюк. The scanf() calls are failing due to not "consuming/gobbling-up" the trailing newline character. Don't use scanf(): use fgets() and the atoX() and sscanf() functions if you must do string parsing like this.strtok() вызов в моей функции getBuf() - это только их вариант, если вы используете этот пример для других типов синтаксического анализа строк в будущем. Функция fgets() не использует общий потокный буфер, например scanf().

Я обновил ваш список кодов и смог получить те же результаты, используя оба предложенных метода расчета мощности.

Листинг


/******************************************************************************* 
* Pre-processor Directives 
******************************************************************************/ 
#include <stdio.h> // printf() 
#include <stdlib.h> // atof() will compile but return zero if this is missing 
#include <math.h> // pow() 
#include <stdbool.h> // bool 

#define PI  M_PI 
#define BUF_LEN  (256) 


/******************************************************************************* 
* Function prototypes 
******************************************************************************/ 
bool getBuf(char* buf); 


/******************************************************************************* 
* Function definitions 
******************************************************************************/ 
int main(void) 
{ 
    //Declared variables 
    float base_area, height_area, total_area_per_container; 
    float radius, height, cost_per_container, total_cost, cost_per_sq_cm; 
    int containers; 
    char buf[BUF_LEN] = { 0 }; 

    // User input 
    //radius input 
    printf("Enter radius of base in cm: "); 
    if (!getBuf(buf)) { return (-1); } 
    radius = atof(buf); 

    //height input 
    printf ("Enter height of container in cm: "); 
    if (!getBuf(buf)) { return (-1); } 
    height = atof(buf); 

    //material cost 
    printf("Enter material cost per square cm: "); 
    if (!getBuf(buf)) { return (-1); } 
    cost_per_sq_cm = atof(buf); 

    //amount of containers 
    printf("Enter the number of containers to be produced: "); 
    if (!getBuf(buf)) { return (-1); } 
    containers = atoi(buf); 

    //calcualtions of each container 
    base_area = PI * pow(radius, 2.0); 
    //base_area = PI * radius * radius; 
    height_area = 2 * PI * radius * height; 
    total_area_per_container = base_area + height_area; 

    //calculation of the cost of the material 
    cost_per_container = total_area_per_container * cost_per_sq_cm; 
    total_cost = containers * cost_per_container; 

    //Print results 
    printf("Surface area of container: %.2f cm\n", total_area_per_container); 
    printf("Cost per container: $%.2f\n", cost_per_container); 
    printf("Total production costs: $%.2f\n", total_cost); 

    //exit program 
    return (0); 
} 

bool getBuf(char* buf) 
{ 
    if (!buf) 
    { 
     printf("Bad input.\n"); 
     return false; 
    } 
    fgets(buf, BUF_LEN, stdin); // Get a string of data 
    strtok(buf, "\n");  // Clear out trailing newline 
    return true; 
} 

Пример вывода


gcc test.c -lm && ./a.out 
Enter radius of base in cm: 1 
Enter height of container in cm: 2 
Enter material cost per square cm: 3 
Enter the number of containers to be produced: 4 
Surface area of container: 15.71 cm 
Cost per container: $47.12 
Total production costs: $188.50 

+0

Cool Thanks @Dogbert Мне нужно будет изучить эти функции! – AndrewDonaldStockton

+0

Звучит неплохо. Если это ответит на ваш вопрос, пожалуйста, нажмите галочку, чтобы отметить ее как принятую, и подтвердите ее, если вы считаете, что она охватывает все, что вы просили. Ура! – DevNull

0

Спасибо всем за ваше время, отвечая на мой вопрос. Настоящим ответом моей проблемы, несмотря на неэффективное использование кода, было следующее:

Я беру новое введение в курс программирования C и отправляю домашнее задание. Я копирую информацию на компьютер учителей, где он проходит тестирование и компиляцию код, который я написал. Я не знаю, почему, но код, когда он проходит этот процесс, со стороны профессоров, похоже, не связан с процессом -lm. это была проблема, математическая библиотека не была связана.

:/мои извинения за путаницу.

Спасибо @Dogbert за улучшенный способ кодирования. Я попытаюсь прочитать свою книгу, чтобы выяснить, что означают функции fgets(), atoX(), sscanf(), getBuff() и strtok().