commoccoom
V2EX  ›  问与答

请教一个《C Primer Plus》上一个代码的问题

  •  
  •   commoccoom · Jan 10, 2021 · 1494 views
    This topic created in 1980 days ago, the information mentioned may be changed or developed.
    /*对用户输入的整数求和*/
    #include <stdio.h>
    
    int main(void)
    {
    	long num;
    	long sum = 0L; 
    	int status;
    
    	printf("Please enter an integer to be summed ");
    	printf("(q to quit): ");
    	status = scanf_s("%1d", &num);  	
    
    	while (status == 1) 
    	{		
    		sum = sum + num;
    		printf("Please enter next integer (q to quit): ");
    		status = scanf_s("%1d", &num);
    	}
    
    	printf("Those integers sum to %1d.\n", sum);
    	return 0;
    }
    

    为什么我的运行结果是不对的啊😂 变成了 1+2+2+3=8

    1.png

    while 语句里面还循环了两次

    5 replies    2021-01-10 16:01:34 +08:00
    QBugHunter
        1
    QBugHunter  
       Jan 10, 2021
    while (status == 1)
    ?????
    Chowe
        2
    Chowe  
       Jan 10, 2021 via iPhone   ❤️ 1
    %1d 表示长度为 1 的整形数
    所以 12 会变成
    1
    2
    更多有关细节,请查阅格式化输入输出
    commoccoom
        3
    commoccoom  
    OP
       Jan 10, 2021
    @Chowe 明白了,多谢!
    msg7086
        4
    msg7086  
       Jan 10, 2021
    你是不是把 ld 打成了 1d ?
    commoccoom
        5
    commoccoom  
    OP
       Jan 10, 2021
    @msg7086 好像是的啊😅
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2804 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 10:41 · PVG 18:41 · LAX 03:41 · JFK 06:41
    ♥ Do have faith in what you're doing.