我的程序試圖模擬自動售貨機。除硬幣退還或退還零件以外的所有零件都可以使用。我試圖把插入到機器中的美分量輸入到主體外的另一個代碼中,然後返回一個字符串。這在C中是可能的,因爲我不斷得到一個初始化使得整型指針沒有轉換錯誤。如果這是不可能的,關於如何做到這一點的任何想法?如何返回字符串變量c
謝謝!
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define NI 5
#define DI 10
#define QU 25
bool isValid(int num) {
return (num >= 10 && num <= 100);
}
bool isMultiple(int num) {
return (num % 5 == 0);
}
char *coinReturn(int insert) {
int dimes = insert/DI;
int remainder = insert % DI;
int nickels = remainder/NI;
int remainder2= nickels % NI;
char *m = ("Change returned. %d nickels and %d dimes\n",nickels, dimes);
return m;
}
int
main (int argc, char *argv[])
{ for (int i = 1; i != argc; ++i) {
int price = atoi(argv[i]);
if (!isValid(price)) {
printf("Price muse be from 10 cents to 100 cents.\n");
break;
} else if (!isMultiple(price)) {
printf("Price must be a multiple of 5.\n");
break;
} else {
printf(" Welcome to my Vending Machine!\n");
printf("Pop is %d cents. Please enter nickels, dimes, or quarters\n", price);
int cents = 0;
char coin = '\0';
while (cents <= price && coin != 'E') {
printf(" PLease enter a coin [NDQR]\n");
scanf (" %c", &coin);
if (coin == 'N'|| coin == 'n') {
cents = cents + NI;
printf(" You have inserted 5 cents\n");
}
else if (coin == 'd' || coin == 'D') {
cents = cents + DI;
printf("You have inserted 10 cents\n");
}
else if (coin == 'Q' || coin == 'q') {
cents = cents + QU;
printf("You have entered 25 cents\n");
}
else if (coin == 'R' || coin == 'r'){
printf("Change requested\n");
char *rtn2= coinReturn(cents);
printf("%s\n",rtn2);
} else {
printf("Unknown coin. Rejected.\n");
}
int balance = price - cents;
printf("You have entered a total of %d cents\n", cents);
if (balance > 0) {
printf("You must enter %d more cents\n", balance);
} else {
char *rtn = coinReturn(cents);
printf("%s\n",rtn);
cents = 0;
}
}
printf("DONE!\n");
return 0;
}
}
但我需要以某種方式返回聲明。我可以用printf來做到這一點? – JVAN
不是。你可以'malloc'緩衝區,使用['snprintf'](http://www.cplusplus.com/reference/cstdio/snprintf/)格式化它,然後返回它。 –
但你所做的所有回報是printf它。爲什麼不直接在函數中執行printf? –