我正在尝试通过遵循以下内容来学习基本的 C 编程textbook我一定遗漏了一些关于数据类型、舍入和/或运算顺序的信息,因为当我尝试构建一个简单的程序将秒转换为小时和分钟时,小时有效,但剩余分钟在它们出现时变为 0不应该是。
谢谢Coursera,我知道这样的程序存在巨大的安全漏洞,但出于学习目的,我会要求您忽略安全性。目前,书籍希望我坚持使用printf
, scanf
, and a 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 专家可以使用更先进的技术以更简洁的形式编写程序的安全版本。如果您想提及的话,这也可能具有教育意义,但首先也是最重要的是,我需要了解这个简单程序的情况。