C - Root не печатает правильное значение, не меняется от суммы - PullRequest
0 голосов
/ 12 октября 2018

Это часть домашнего задания, в котором пользователь вводит пять целых, и оно проходит через несколько функций, получая сумму, среднее значение, sqrt и пару других вещей.Вот код:

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

// needs to be declared in order to work
int functionPrint(int sum, int root);

//sum function, takes all the ints from main and sums it up
int functionSum(int one, int two, int three, int four, int five) {
    int sum = one + two + three + four + five;
    // sends the sum to the print function
    sum = functionPrint(sum, sum);
}

//sqrt function, will take all numbers and square root them
int functionSqrt(int one, int two, int three, int four, int five) {
    int root = sqrt(three);
    // sends the sqrt numbers to print
    root = functionPrint(root, root);
}

int functionPrint(int sum, int root) {
    printf("Sum: %d\n", sum);
    printf("Square Root: %d\n", root);
}

//main function, all values to be worked are created here and sent to the other functions
int main() {
    int sumMain, one, two, three, four, five;

    printf("Enter five numbers separated by spaces: ");
    scanf("%d%d%d%d%d", &one, &two, &three, &four, &five);

    sumMain = functionSum(one, two, three, four, five);
}

В настоящее время предполагается распечатать только сумму и sqrt из int трех (я включу другие целые числа, когда я это исправлю).functionPrint() начинается со строки 21, а functionSqrt() начинается со строки 15. Но, как я уже сказал, он печатает только сумму.Я предполагаю, что существует какая-то переменная, которая должна быть перезаписана, или что-то в этом роде.Но опять же, я не эксперт.

Любая помощь будет оценена

Ответы [ 3 ]

0 голосов
/ 12 октября 2018
  1. В main ()

    scanf("%d%d%d%d%d", &one, &two, &three, &four, &five);
    

scanf () не будет работать так, как вы хотите, в строке формирования нет определенного разделителя ("% d%d% d% d% d "), как бы вы поделили свои 5 входов?

В main ()

sumMain = functionSum(one, two, three, four, five);

sumMain не получит нужное значение суммы, потому что functionSum () не "возвращает" никакое значение, пожалуйста, GoogleЯзык C "+" возврат "самостоятельно.

измененные функции functionSum () и functionSqrt () в соответствии с результатами поиска на шаге 2. Возможно, вам не понадобится functionPrint ().
0 голосов
/ 12 октября 2018

Добавьте #include <stdlib.h> и измените scanf на:

int result = scanf("%d%d%d%d%d", &one, &two, &three, &four, &five);
if (result != 5)
{
    fprintf(stderr, "Error, failed to read five numbers.\n");
    exit(EXIT_FAILURE);
}

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

Измените functionSum на , верните значение.functionSum объявлен с int functionSum(…), что означает, что он должен возвращать значение.Чтобы на самом деле вернуть значение, вам нужно вставить в него оператор return:

int functionSum(int one, int two, int three, int four, int five)
{
    return one + two + three + four + five;
}

В программе main вызовите functionPrint после functionSum:

sumMain = functionSum(one, two, three, four, five);
functionPrint(sumMain, 0);

Это должно позаботиться о расчете суммы и ее печати.Понимание этих изменений должно помочь вам достичь квадратного корня.

0 голосов
/ 12 октября 2018

Модификация Сделано в вашей программе согласно требуемому выводу:

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

// needs to be declared in order to work
int functionPrint(int sum, int root);

//sum function, takes all the ints from main and sums it up
int functionSum(int one, int two, int three, int four, int five) {
    int sum = one + two + three + four + five;
    float sqrt = functionSqrt(one,two,three,four,five);  // Called the Sqrt function and receives the square root of the third number
    // sends the sum to the print function
    sum = functionPrint(sum, sqrt);
}

//sqrt function, will take all numbers and square root them
int functionSqrt(int one, int two, int three, int four, int five) {
    int root = sqrt(three);
    return root;
    // sends the sqrt numbers to print
  //  root = functionPrint(root, root);
}

int functionPrint(int sum, int root) {
    printf("Sum: %d\n", sum);
    printf("Square Root: %d\n", root);
}

//main function, all values to be worked are created here and sent to the other functions
int main() {
    int sumMain, one, two, three, four, five;

    printf("Enter five numbers separated by spaces: ");
    scanf("%d%d%d%d%d", &one, &two, &three, &four, &five);

    sumMain = functionSum(one, two, three, four, five);
}
...