gpt4 book ai didi

c - 在数组中存储值

转载 作者:太空宇宙 更新时间:2023-11-04 03:51:31 25 4
gpt4 key购买 nike

我的作业需要一些帮助。我需要创建一个数组 amounts 来存储五个元素,然后创建两个包含五个元素的数组,名称为美元和美分。我的问题是我无法理解如何将金额数组中每个值的整数部分存储在相应的美元元素中,并将金额的小数部分存储为以美分为单位的两位整数(就像我输入 2.75 - 存储2美元阵列和75美分阵列)。任何关于如何做到这一点的建议将不胜感激!谢谢

这是我目前拥有的:

void main()
{
float amounts[5];
long dollars[5];
long cents[5];
int i = 0;

printf("Enter five monetary values separated by spaces:\n");
for(i = 0; i<5 ; i++)
scanf("%f", &amounts[i]);

for (i = 0; i<5; i++){

printf ("\ni=[%d], dollars: %.2f, cents: %.2f\n", i, dollars, cents);
}
printf("\nYou entered the values: \n");

for(i = 0; i<5 ; i++)
printf("$%.2f\n", amounts[i]);
printf("\n");

}

最佳答案

dollars[i] = (long)(amounts[i]) 会截断它,即去掉小数部分。

cents[i] = (long)((amounts[i] - dollars[i]) * 100); 会将小数部分作为整数给出。

关于c - 在数组中存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319471/

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