如何编写使用其他函数值的函数

时间:2016-07-23 08:42:26

标签: c function

我是c的初学者,所以请给我尽可能简单的建议。 我有两个问题。你如何在带指针的函数中使用scanf,因为我的程序根本不工作。 另外,如何编写使用其他函数值的函数。例如,我必须编写一个函数,询问员工姓名,工作小时数和小时费率。然后我必须编写另一个使用该信息计算总薪酬和加班费的函数。 这是我到目前为止写的scanf代码:

#include <stdio.h>
     #include <stdlib.h>
     int employeedata(char *ch, float *x, float *y)
      {
      printf("Enter your name:\n");
       scanf_s("%s", &ch);
      printf("Enter your hourly rate:\n");
      scanf_s("%f", &x);
       printf("Enter number of hours worked:\n");
       //variables
           scanf_s("%f", &y);
      }
  int main() {

           float rate[5], hours[5];
       float overtimerate = 1.5;
       char name[5][20];

           int loop;

           //loop 5 times
           for (loop = 0; loop < 5; loop++)
           {
            //call function
                employeedata(name[loop], &rate[loop], &hours[loop]);
           //use if to break out of loop after input if -1 is entered
                if (strcmp(name, "-1") == 0)
                 break;

                if (rate[loop] == -1)
                 break;

               if (hours[loop] == -1)
                 break;
            }
        system("pause");
        return 0;

}

2 个答案:

答案 0 :(得分:1)

您正在将指针传递给行中的scanf函数中的指针

scanf_s("%s", &ch);

scanf需要指向要在其中放置读取值的存储区的指针。因此,更正后的代码应为

scanf_s("%s", ch);

行中的错误

 scanf_s("%f", &x);
 scanf_s("%f", &y);

必须是

 scanf_s("%f", x);
 scanf_s("%f", y);

因为x,y&amp; ch本身就是指针

更多: 这是scanf()

的原型
  

int scanf(const char *format_string, ...);

其中"..."(省略号)指的是指向桶的指针。

答案 1 :(得分:0)

编辑:这是您想要的所有内容的示例

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

char *inputString(FILE* fp, size_t size) {
    //The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(char)*size);//size is start size
    if (!str)return str;
    while (EOF != (ch = fgetc(fp)) && ch != '\n') {
        str[len++] = ch;
        if (len == size) {
            str = realloc(str, sizeof(char)*(size += 16));
            if (!str)return str;
        }
    }
    str[len++] = '\0';
    return realloc(str, sizeof(char)*len);
}


void CalcFunc(double hours, double rate, double* gross, double* otime);





int main(void) {
    char *name;
    double HoursWorked = 0, RatePerHour = 0, GroosPay =0, OverTime=0;
    printf("input name: ");
    name = inputString(stdin, 10);


    printf("input hours worked: ");
    scanf("%lf", &HoursWorked);

    printf("input rate per hour: ");
    scanf("%lf", &RatePerHour);

    CalcFunc(HoursWorked, RatePerHour, &GroosPay, &OverTime);
    printf("Name:%s\n", name);
    printf("hours worked:%.2f\n", HoursWorked);
    printf("rate per hour:%.2f\n", RatePerHour);
    printf("over time:%.2f\n", OverTime);
    printf("gross pay:%.2f\n", GroosPay);

    free(name);
    return 0;
}



void CalcFunc(double hours, double rate, double* gross, double* otime) {
//just an example for function
    *otime = hours*2;
    *gross = hours*rate*0.3;
    return;
}