表达式中的赋值?

时间:2018-03-09 03:13:19

标签: c++

这段代码相当于什么?

int sec, mins, hours, days;
cin >> sec;
sec -=  (60 * 60 * 24) * (hours = sec / (60 * 60 * 24));
sec -=  (60 * 60) * (days = sec / (60 * 60));
sec -=  60 * (mins = sec / 60);

此代码由我的朋友编写,用于计算以秒为单位输入的输入中的天数,小时数,分钟数。这对我来说似乎很模糊。

sec -=  (60 * 60 * 24) * (hours = sec / (60 * 60 * 24));

为什么这条线意味着什么?我对单个表达式中的两个赋值感到困惑。嵌入式赋值在标准c ++中是否有效?无论整个代码如何。

4 个答案:

答案 0 :(得分:4)

该行

sec -= (60 * 60 * 24) * (hours = sec / (60 * 60 * 24));

相当于

hours = sec / (60 * 60 * 24);
sec -= (60 * 60 * 24) * hours;

构造(a = b)被视为表达式,它返回值b。以下是几个等效表达式的例子:

5
4 + 1
2 * 2 + 1
2 * 2 + (a = 1)

所以一切顺利!那就是说......不要写这样的代码。

答案 1 :(得分:0)

=运算符接收两个参数,将右侧的参数分配给左侧,并返回分配的值。记住,二元运算符只是二进制函数

示例:

#include <iostream>

int main()
{
    int i;
    std::cout << (i = 42);
}

输出:

42

(ideone)

答案 2 :(得分:0)

秒 - =(60 * 60 * 24)*(小时=秒/(60 * 60 * 24));

等于:

   days = sec / (60 * 60 * 24);
   days_secs = (60 * 60 * 24) * days;
   sec -= days_secs;

变量&#34;小时&#34;不是很漂亮,它应该是&#34;天&#34;。 同样,变量&#34;天&#34;在

sec -=  (60 * 60) * (days = sec / (60 * 60));

应该是&#34;小时&#34;。

祝你好运。

答案 3 :(得分:0)

首先,小时和天数变量混淆,天应该先行。我认为用一个变量替换所有这些数字有助于:

#include <iostream>

#define secondsInaDay (60 * 60 * 24)
#define secondsInAnHour (60 * 60)
#define secondsInAMinute 60

int main() 
{
    int totalSeconds, mins, hours, days;
    cin >> totalSeconds;

    totalSeconds -= (secondsInaDay) * (days = totalSeconds / (secondsInaDay));
    // First divides the total seconds by the seconds in a day, giving the number of days.
    // Then subtracts the seconds that have been accounted as days on the left side.

    totalSeconds -= (secondsInAnHour) * (hours = totalSeconds / (secondsInAnHour));
    // First divides the remaining seconds by seconds in an hour, giving the number of hours.
    // Then subtracts the seconds that have been accounted for as hours.

    totalSeconds -= secondsInAMinute * (mins = totalSeconds / secondsInAMinute);
    // First divides the remaining seconds by seconds in a minute to give the number of minutes
    // Then subtracts the seconds that have been accounted for as minutes.

    int seconds = totalSeconds;
    // Any remaining seconds are added to seconds

    return 0;
}