【发布时间】:2015-07-16 18:34:03
【问题描述】:
我正在尝试通过遵循textbook 来学习基本的 C 编程,但我一定会遗漏一些关于数据类型、舍入和/或操作顺序的内容,因为当我尝试构建一个简单的程序来将秒转换为小时和分钟,小时有效,但剩余的分钟数不应该为 0。
感谢Coursera,我知道此类程序存在巨大的安全漏洞,但出于学习目的,我会要求您忽略安全性。目前,这些书希望我坚持使用printf、scanf 和while 循环,因为它们与我正在阅读的教科书的章节相对应(这些书让我知道我会读到当我再读几章时开始担心安全性。
我的 C 程序如下所示:
/* Ask the user for a number of seconds, convert to X hours and Y minutes */
/* Continue doing this with a while loop until user enters 0 */
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main(void)
{
const int minperhour = 60;
const int secpermin = 60;
int sec, hr;
float min;
sec = 1;
while(sec != 0)
{
printf("Enter the number of seconds to convert: \n");
scanf("%i", &sec);
min = sec/secpermin;
hr = min/minperhour;
min = (sec/secpermin) - (hr * minperhour);
printf("%d hours and %f minutes \n", hr, min);
}
return 0;
}
我希望我可以输入3601,结果将是:
1 hours and 0.01667 minutes
因为这是在我更熟悉的 R 语言中计算表达式的方式:
> min = 3601/60
> min
[1] 60.02
> hr = min/60
> hr
[1] 1
> min = (3601/60) - (1 * 60)
> min
[1] 0.01667
但是,我在 C 中得到的是:
C:\Users\hackr>pa2q3.exe
Enter the number of seconds to convert:
3601
1 hours and 0.000000 minutes
Enter the number of seconds to convert:
7205
2 hours and 0.000000 minutes
Enter the number of seconds to convert:
0
0 hours and 0.000000 minutes
C:\Users\hackr>
我投了7205第二次尝试只是为了更好的衡量。
我感觉 Stack Overflow 上的一些 C 大师可以使用更先进的技术以更简洁的形式编写程序的安全版本。如果您想提及它,这也可能具有教育意义,但首先我需要了解这个简单程序发生了什么。
【问题讨论】:
标签: c