typedef struct add_stock
{
char name[30];
int share;
float price;
float total;
} add_stock;
FILE *fp;
add_stock *a;
int n, i, j;
printf("Hover the cursor on the URL and click (ctrl click) to know the d/b shares and stocks and then later on fill the further information as ask https://youtu.be/AeEgoc3k_0o");
printf("Enter the no. of stocks you have purchased : ");
scanf("%d", &n);
a = (add_stock *)calloc(n, sizeof(add_stock));
fp = fopen("myportfolio.txt", "a");
for (i = 0; i < n; i )
{
a[i].total = 0;
printf("Enter the name of the company : ");
scanf(" %[^\n]", a[i].name);
printf("Enter how many shares you have bought : ");
scanf("%d", &a[i].share);
printf("Enter the price of each share : ");
scanf("%f", &a[i].price);
fprintf(fp, "\n%s \n%d \n%f", a[i].name, a[i].share, a[i].price);
a[i].total = a[i].share * a[i].price;
fprintf(fp, "\n%f", a[i].total);
}
fclose(fp);
我想要的是,我得到一個用戶投資的總金額的總和。目前,它只給我投資于特定公司的總金額。但我也想要投資于所有公司的總金額。我希望你能明白我的意思。
前公司:特斯拉,股數:2,每股價格:200.000000,股票投資總額:400.000000
公司:蘋果,股數:2,每股價格:300.000000,股票投資總額:600.000000
現在,我想要的 => 400 600 = 1000。
uj5u.com熱心網友回復:
...
float portfolio_total_value = 0.0f ; // <<<< Before your input loop
for (i = 0; i < n; i )
{
...
a[i].total = a[i].share * a[i].price;
portfolio_total_value = a[i].total ; // <<<< Accumulate total in the input loop
...
}
// >>> Output the total *after* the input loop <<<<
fprintf( fp, "\nPortfolio value: %f\n", portfolio_total_value ) ;
但是,要獲得正確的解決方案,您還需要更改:
unsigned int total;
到
float total;
uj5u.com熱心網友回復:
只需添加另一個變數
fp = fopen("myportfolio.txt", "a");
int grandTotal = 0;
然后在回圈中
a[i].total = a[i].share * a[i].price;
grandTotal = a[i].total;
fprintf(fp, "\n%f", a[i].total);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464196.html
標籤:C
上一篇:在C中使用PCWSTR
