【问题标题】:Why is the second of two while loops with identical condition not working?为什么具有相同条件的两个 while 循环中的第二个不起作用?
【发布时间】:2021-01-30 09:33:28
【问题描述】:

我现在正在参加 CS50 Introduction to CS。我试图解决 Set 1,Credit。该程序尚未完成,我只是想确保它正确计数。有我的代码,它取自用户输入,它是一个正数。第一个while循环计算倒数第二个数字并将它们加在一起并给出输出,第二个while循环计算每个最后一个数字并相加。

如果我单独运行它们,那么两个 while 循环都会正确计数。就我而言,现在它只计算第一个时间。 我会感谢你的帮助!

#include  <stdio.h>
#include <cs50.h>

int main(void)
{
    long credit;
    int multiply_by_two, sum_by_two = 0, sum = 0;
    do
    {
        credit = get_long("Number: ");
    }
    while (credit < 0);

    while (credit != 0)
    {
        long second_digit =  credit / 10;
        long last_digit = second_digit % 10;
        multiply_by_two = last_digit * 2;
        if (multiply_by_two > 9)
        {
            sum_by_two += multiply_by_two % 10 + multiply_by_two / 10;
        } else
        {
            sum_by_two += multiply_by_two;
        }
        credit = credit /100;
    }
    while (credit != 0)
    {
        long first_digit = credit % 10;
        sum += first_digit;
        credit = credit / 100;
    }
    printf("First total sum: %d\n", sum_by_two);
    printf("Second total sum: %d\n", sum);
}

【问题讨论】:

    标签: c cs50


    【解决方案1】:

    第一个while (credit != 0)显然以credit==0结尾。
    第二个while (credit != 0) 确保只有在credit != 0 时才执行主体。

    您可能希望第二个循环处理初始 credit 的副本,而不是保证为 0 的内容。

    (这里故意不提供解决方案,因为
    How do I ask and answer homework questions?

    【讨论】:

    • 哦对了!这就是问题所在。非常感谢!
    • 您知道stackoverflow.com/help/someone-answers 吗?它不需要您接受答案,尤其是我的答案。但是,有了像您这样的赞赏评论,您可能想要解释缺少的内容...
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 2019-11-08
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多