gpt4 book ai didi

c - 为什么我的函数中的数据没有传回 Main?

转载 作者:行者123 更新时间:2023-11-30 19:26:36 25 4
gpt4 key购买 nike

编写一个程序,接受用户输入并通过一些函数运行它。我无法更改其中一个函数中的数据来更改主函数中的变量数据。

#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语句显示的内容与调用之前的相同。

最佳答案

在 C 语言中,值通过两种方式传递给函数:

  1. 按值传递
  2. 通过引用传递

请参阅本文了解更多信息:

https://www.geeksforgeeks.org/difference-between-call-by-value-and-call-by-reference/

关于c - 为什么我的函数中的数据没有传回 Main?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56925270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com