kk-Exercise 5.3 Handling monetary values as integers

Exercise 5-3. Write a program that will read five values from the keyboard and store
them in an array of type float with the name amounts. Create two arrays of five
elements of type long with the names dollars and cents. store the whole number part
of each value in the amounts array in the corresponding element of dollars and the
fractional part of the amount as a two-digit integer in cents (e.g., 2.75 in amounts[1]
would result in 2 being stored in dollars[1]  and 75 being stored in cents[1] ). Output
the values from the two arrays of type long as monetary amounts (e.g., $2.75).

对着打出错

 

 1 //Exercise 5.3 Handling monetary values as integers
 2 #include <stdio.h>
 3 
 4 int main(void)
 5 {
 6   const size_t size = 5;
 7   float amounts[size];                     // Stores data values
 8   long dollars[size];
 9   long cents[size];
10   int i = 0;
11 
12   printf("Enter %zd monetary values separated by spaces:\n", size);
13   for( i = 0 ; i < size ; ++i)
14     scanf("%f", &amounts[i]);
15 
16   for( i = 0 ; i < size ; ++i)
17   {
18     dollars[i] = (long)amounts[i];
19     cents[i] = (long)(100.0*(amounts[i] - dollars[i]));// 注意这里是100.0不是100
20   }
21 
22   printf("\n");
23   for( i = 0 ; i < size ; ++i)
24     printf("  $%d.%02d", dollars[i], cents[i]);
25 
26   printf("\n");
27   return 0;
28 }

 做了几次,老出错,竟然没有发现问题在哪里!

转载于:https://www.cnblogs.com/xiaomi5320/p/4188623.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值