为什么两个条件相同的while循环中的第二个不起作用? [英] Why is the second of two while loops with identical condition not working?

查看:63
本文介绍了为什么两个条件相同的while循环中的第二个不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在学习CS50 CS简介.我试图解决Set 1,Credit.该程序尚未完成,我只是想确保它能正确计数.有我的代码,它取自用户输入,它是一个正数.第一个while循环计数每个倒数第二个数字并将它们加在一起并提供输出,第二个while循环计数每个倒数第二个数字也添加.

I am taking CS50 Introduction to CS right now. I trying to solve Set 1, Credit. The program is not completed yet, I just wanted to make sure that it counts correctly. There is my code, it takes from the user input which is a positive number. 1st while loop counts every second-to-last digit and add them all together and gives output, 2nd while counts every last digit and adds as well.

如果我分别运行,虽然while循环都正确计数.就我而言,现在只算第一次.感谢您的帮助!

Both while loops count correctly if I run them separately. In my case now it counts only the first while. I will appreciate your help!

#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);
}

推荐答案

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

The first while (credit != 0) obviously ends with credit==0.
The second while (credit != 0) makes sure that the body is only executed when, you know, credit != 0.

您可能打算让第二个循环处理初始 credit 的副本,而不是保证为0的副本.

You probably intend the second loop to work on a copy of the initial credit instead of something guaranteed to be 0.

(由于
,有意在此不提供解决方案如何提出和回答作业问题?)

这篇关于为什么两个条件相同的while循环中的第二个不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆