编写一个程序,接受用户输入并通过一些功能运行它。我无法在其中一项功能中更改数据以更改主数据。
#include <stdio.h>
int convertLoot (int gold , int silver , int bronze, int total);
int convertBronze (int total, int gold, int silver, int bronze);
int Spend (int total);
int main()
{
int gold, silver, bronze, total, *Ntotal ;
Ntotal= &total;
printf("Please enter loot amounts.\n");
printf ("Gold>");
scanf("%d", &gold);
printf ("Siver>");
scanf("%d", &silver);
printf("bronze>");
scanf("%d", &bronze);
convertLoot ( gold, silver, bronze, total );
printf("total is %d bronze \n", *Ntotal);
convertBronze(total, gold, silver, bronze);
printf("Total loot is %d gold %d silver %d bronze \n", gold, silver, bronze);
Spend ( total);
convertBronze(total, gold, silver, bronze);
printf("total is %d bronze \n", *Ntotal);
printf("Total loot is now %d gold %d silver %d bronze \n", gold, silver, bronze);
return (0);
}
// Converts loot in bronze.
int convertLoot (int gold, int silver, int bronze, int total)
{
int conGold= gold*100;
int conSilver=silver*10;
int conTotal=conGold+conSilver+bronze;
total=conTotal;
return 0;
}
//Convert Bronze Function.
//Take Total Bronze and reconverts it to Gold Silver and Bronze.
int convertBronze (int total, int gold, int silver, int bronze)
{
gold=total/100;
total=total%100;
silver=total/10;
bronze=total%10;
return 0;
}
// spend function
int Spend (int total)
{
int SubGold;
int SubSilver;
int SubBronze;
int Choice;
int *Ntotal;
Ntotal= &total;
printf("What do you wish to spend? \n");
printf("1 for Gold , 2 for Silver, 3 for Bronze \n");
scanf("%d", &Choice);
if (Choice== 1){
printf("How much Gold? \n");
scanf ("%d" , &SubGold);
*Ntotal=total-(SubGold*100);
return 0;
}
else if (Choice== 2){
printf("How munch Silver? \n");
scanf("%d" , &SubSilver);
*Ntotal=*Ntotal-(SubSilver*10);
}
else if (Choice== 3){
printf("How much Bronze? \n");
scanf("%d" , &SubBronze);
*Ntotal=*Ntotal-(SubBronze);
return 0;
}
}
来自Spend函数的更改,对main中的“ total”变量没有影响。支出函数调用之后的第二个printf语句显示与调用之前相同的内容。
答案 0 :(得分:0)
在C语言中,可以通过两种方式将值传递给函数:
请参阅此文章以获取更多信息:
https://www.geeksforgeeks.org/difference-between-call-by-value-and-call-by-reference/