【发布时间】:2016-11-24 17:31:55
【问题描述】:
我正在尝试创建一个存储不同值并通过指针引用它们的结构,并在函数中使用该指针,但是一旦我将指针传递给函数,它似乎会丢失原始数据中的所有数据结构指针也指向。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#pragma warning(disable:4996)
void clear_screen();
void stopE();
void cost(struct coffee *cust1);
void reciept(char name[], int coff, int tea, double total, double noTax);
double noTax(struct coffee *cust1);
struct coffee
{
char name[21];
int cCups;
int tCups;
double totalCost;
};
void main()
{
char buffer[10] = {0};
struct coffee cust;
printf("Please input the customers name: ");
gets(cust.name);
printf(" \nPlease enter how many cups of coffee ordered: ");
gets(buffer);
cust.cCups = atoi(buffer);
stopE();
printf(" \nPlease enter how many cups of tea ordered: ");
gets(buffer);
cust.tCups = atoi(buffer);
stopE();
struct coffee *cust1 = &cust;
clear_screen();
double withoutTax = noTax(&cust1);
cost(&cust1);
reciept(cust.name, cust.cCups, cust.tCups, cust.totalCost, withoutTax);
}
void stopE()
{
int c = getchar();
while (c != EOF && c != '\n')
{
c = getchar();
}
}
void cost(struct coffee *cust1)
{
double a = (double)cust1->cCups*1.75;
double b = (double)cust1->tCups * 1.5;
double inter = a + b;
double totalCost = inter + (inter*0.13);
cust1->totalCost = totalCost;
}
double noTax(struct coffee *cust1)
{
double totalCost = (cust1->cCups*1.75) + (cust1->tCups*1.5);
return totalCost;
}
void reciept(char name[], int coff, int tea, double total, double noTax)
{
printf("Coffee Co.\n");
srand(time(NULL));
int r = rand() % 101;
printf("Order Number: %d\n", r);
printf("Name: %s\n", name);
for (int i = 0; i < coff; i++)
{
printf("Coffee: $1.75\n");
}
for (int i = 0; i < tea; i++)
{
printf("Tea: $1.50\n");
}
printf("Total without tax: $%.2f", noTax);
printf("\n13%% Tax total: $%.2f", (noTax*0.13));
p
rintf("\nTotal: $%.2f\n", total);
getchar();
}
void clear_screen(void)//Function to clear screen
{
DWORD n; /* Number of characters written */
DWORD size; /* number of visible characters */
COORD coord = { 0 }; /* Top left screen position */
CONSOLE_SCREEN_BUFFER_INFO csbi;
/* Get a handle to the console */
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(h, &csbi);
/* Find the number of characters to overwrite */
size = csbi.dwSize.X * csbi.dwSize.Y;
/* Overwrite the screen buffer with whitespace */
FillConsoleOutputCharacter(h, TEXT(' '), size, coord, &n);
GetConsoleScreenBufferInfo(h, &csbi);
FillConsoleOutputAttribute(h, csbi.wAttributes, size, coord, &n);
/* Reset the cursor to the top left position */
SetConsoleCursorPosition(h, coord);
}
如果有人可以帮助我,将不胜感激,我无法弄清楚如何将数据传递给函数。
编辑:编译指示是使用 scanf 删除错误,因为它不安全而阻止我运行我的程序。
【问题讨论】:
-
double withoutTax = noTax(&cust1);-->double withoutTax = noTax(cust1);,不需要传递地址,因为cust1已经是一个指针了。 -
您的编译器会收到哪些警告?修复它们!特别是。那些看起来像
'coffee *' differs in levels of indirection from 'coffee **'。